skip to Main Content

I am storing images in storage/app/public directory of laravel project.
Also I am saving names of images in the phpmyadmin database if it could be somehow helpful.

Now I want to display those images in my jsx like:

 <div className={"dashboard-cards-cardsContainer"}>
      {
            this.state.images.map((image) =>
               <img key={image.id} src={asset("storage/image.name")}/>
            )
       }
 </div>

I already tried:

<img key={image.id} 
src={'http://localhost:8000/storage/app/'+image.name}}/>

<img key={image.id} 
src={'localhost:8000/storage/app/public'+image.name}}/>

<img src={'../../../../../storage/app/public'+image.name} alt=""/>

The only time I was able to display image was when I was importing them from public folder

import photo from '../../../../../public/assets/cards/card-1.png';

however my images are in laravel storage but I just don’t how to access it from react, I already tried:

import img from '../../../../../storage/app/public/card51564153446.jpeg';
//via storage symlink
import foto from '../../../../../public/storage/card51564153446.jpeg';

How to I access laravel storage via react ?

3

Answers


  1. You can not access directly to your server storage from your React application. You have to use the URL of the image returned by the server (more info here https://laravel.com/docs/5.4/filesystem#file-urls) and use it to fill the src attribute of the img tag

    Login or Signup to reply.
  2. I am just updating @Emaueles answer to show how I solved mine.

    I am running a local server and still have to deploy the app to Heroku so basically the settings will change after some time when I deploy. And boom, I’d have to change the URL prefix to my deployment one. I am storing images in the public folder coz my app is not that image-intensive but the solution would work even for images uploaded in storage.

    In my resources/views/index.blade.php(serves as my base HTML file). I add the base URL to my image storage as below

    ...
    <body>
        <div id="app" data="{{ session('message') }}"
            @if(Route::has('https'))
                <!-- scure asset to fetch from https -->
                assetPath="{{secure_asset ('/')}}">assetPath="{{asset ('/images')}}"
            @else
                assetPath="{{asset ('/')}}"
            @endif
            >
        </div>
        <script src="/js/app.js"></script>
    </body>
    ...
    

    Reason for this is Heroku requires HTTPS but my local will work with HTTP.
    Then we can retrieve it as a prop in the index.js file and pass it to other Components.

    resources/js/index.js

    Import React from 'react;
    import ReactDOM from "react-dom";
    import Routes from "./routes";
    
    if (document.getElementById("app")) {
        const assetPath = document.getElementById("app").getAttribute("assetPath");
        ReactDOM.render(<Routes assetPath={assetPath} />, 
          document.getElementById("app"));
    }
    

    resources/js/routes.js

    ...
    const Routes = ({ data, csrf, assetPath }) => (
      <BrowserRouter>
        <Header assetPath={assetPath} />
        <Switch>
            <Route
                exact
                path="/"
                render={() => <Home assetPath={assetPath} />}
            />
            <Route component={NotFound} />
        </Switch>
        <Footer />
      </BrowserRouter>
     );
    ...
    

    Then I’ll use it in any component like:

    ...
    const Header = ({assetPath}) => (
      <img src={`${assetPath}/my-image.png`} />
    )
    ...
    

    To add an image in Css, just place it in the public/images folder. Go to your css and say you need to add some background image…

    ...
    .my-element {
      background: url(/images/myImage.png);
    }
    ...
    
    Login or Signup to reply.
  3. When sending request from ReactJS to PHP, you should manage CORS errors, else You will get errors while sending requests, so create one file named Cors.php file inside the Middleware folder (app/http/middlewares/Cors.php). and write the bellow lines of permissions in the Cors.php as follows:

           <?php
           namespace AppHttpMiddleware;
           use Closure;
           class Cors
              {
               /**
                   * Handle an incoming request.
                   *
                   * @param  IlluminateHttpRequest  $request
                   * @param  Closure  $next
                   * @return mixed
                 */
               public function handle($request, Closure $next)
            {
                  //ALLOW OPTIONS METHOD
                      return $next($request)
                     ->header('Access-Control-Allow-Origin',"*")
                    ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, 
               DELETE, OPTIONS')
                   ->header('Access-Control-Allow-Headers',' Origin, Content-Type, 
           Accept, Authorization, X-Request-With');
           
            }
         }
    

    Now call the Cors.php file inside Kernel.php using this line of code AppHttpMiddlewareCORS::class. (app/http/Kernel.php).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search