2

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 ?

1
  • You have to provide full path of the image in src attribute. Commented Jul 26, 2019 at 16:39

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

I did it, thanks, I actually had to generate url in server-side put in db then fetch url from react and put it in img src tag as you said
i have same issue but i don't want to use url method for each image and return the url
Well, you may put the images needed in a public directory, accessible from outside. Something like, if you are using Apache, to the default wwwroot or htdocs directory.
1

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);
}
...

Comments

0

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 App\Http\Middleware;
       use Closure;
       class Cors
          {
           /**
               * Handle an incoming request.
               *
               * @param  \Illuminate\Http\Request  $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 \App\Http\Middleware\CORS::class. (app/http/Kernel.php).

Comments

0

Should to store data in public folder with this.

$path = $file->move('images/', $file->getClientOriginalName());

And to display it

<img src={`http://localhost:8000/images/${image}`} alt="product-img" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.