Storing files on the same server where your application lives is not a good practice but a simple application may not necessarily require using cloud storage such as AWS S3 and Cloudinary, and files may be stored locally. Storing files locally and displaying them may be a little tricky than we could imagine.
Saving files on the local server
Using the default filesystem configuration for Laravel (config/filesystem
), files are saved in thestorage/app
directory. So when you upload a file using the storage facade, it is saved in this directory. For example:
Storage::put($filename, $file, 'public');
will save the file$file
in the directorystorage/app
with name as$filename
. i.e.app/storage/$filename
and will havepublic
visibility.
Displaying Files stored on the server:
As stated earlier, files are by default stored in thestorage/app/
directory. This prevents files from beenpublicly
accessible (that is, anyone assessing your files over the internet without needing permission).
So to display files in our application from the storage directory correctly, we will create a symbolic link to the public directory using the following artisan command:
php artisan storage:link
Using the helper functionasset
, we can display this file in our application. For example, to use this in the img tag,
<img src=“{{asset($filename)}}” alt=“{{$filename}}” />
so, what happens when you choose to store files outside this default directory saystorage/app/myfiles
? Laravel offers the option of linking this directory to the public directory as well.
To create a symlink from this subdirectory to thepublic
directory, open theconfig/filesystems
file and add the link,
'links' => [ public_path(‘myfiles’) => storage_path('app/myfiles’), ],
then run the commandphp artisan storage:link
this will create a symlink calledmyfiles
in thepublic
directory.
With this, we can be able to access files in this subdirectory with the asset helper as follows:
For example, say you want to access a file stored asdisplay.jpeg
instorage/app/myfiles/
subdirectory, all we need to do is call theasset
helper as below:
<img src=“{{asset(‘myfiles/display.jpeg’)}} alt=“myimage’/>
this is applicable when you have subdirectories in themyfiles
subdirectory. Something likestorage/app/myfiles/subdirectory/display.jpeg
, just specify in the url as follows:
<img src=“{{asset(‘myfiles/subdirectory/display.jpeg’)}}” alt=“my image” />
Also, remember if you did not add the storage directory to yourgit ignore
and it’s pushed, you need to delete it on the server before running the storage link command.
Thanks for reading as I welcome your observations and comments.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse