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
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 theimg
tagI 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
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
resources/js/routes.js
Then I’ll use it in any component like:
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…
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:
Now call the Cors.php file inside Kernel.php using this line of code AppHttpMiddlewareCORS::class. (app/http/Kernel.php).