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 the storage/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 directory storage/app
with name as $filename
. i.e. app/storage/$filename
and will have public
visibility.
Displaying Files stored on the server:
As stated earlier, files are by default stored in the storage/app/
directory. This prevents files from been publicly
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 function asset
, 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 say storage/app/myfiles
? Laravel offers the option of linking this directory to the public directory as well.
To create a symlink from this subdirectory to the public
directory, open the config/filesystems
file and add the link,
'links' => [
public_path(‘myfiles’) => storage_path('app/myfiles’),
],
then run the command php artisan storage:link
this will create a symlink called myfiles
in the public
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 as display.jpeg
in storage/app/myfiles/
subdirectory, all we need to do is call the asset
helper as below:
<img src=“{{asset(‘myfiles/display.jpeg’)}} alt=“myimage’/>
this is applicable when you have subdirectories in the myfiles
subdirectory. Something like storage/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 your git 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)