How to Save Image Files Using Laravel Storage
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
This article summarizes how to save image files using Laravel storage.
The content mainly follows the official documentation:
Creating a Symbolic Link with a Command
php artisan storage:link
Running this command links the files in /storage/app/public/
to /public/storage/
, allowing you to access them via /storage/filename.png
, for example.
When saving image files, the program should store them in /storage/app/
and delete them from there, rather than directly modifying the contents of the /public
directory. This setup ensures proper file management.
After running the command, a non-accessible storage
file will appear in the /public
directory.
To verify the setup, run the following command:
ls -la public
Since public
refers to the public
directory, make sure to specify the relative path correctly from the directory where you run the command.
For example, in my case, the result was:
lrwxr-xr-x 1 root root 32 Feb 4 04:30 storage -> /var/www/html/storage/app/public
This confirms that the link has been successfully created.
Writing Routes and Controllers
Routing
Route::post('/profile', [ProfileController::class, 'update'])->name('profile.update');
Controller
For example, if the users
table has a column named image_url
, the following code can be used:
use Illuminate\Support\Facades\Storage;
~~~~~~
public function update(Request $request)
{
$user = $request->user();
$image = $request->file('image');
// Save the image if one was uploaded
if($image){
// Saved path
$image_url = Storage::disk('public')->put('user_profile_image', $image, 'public'); // Save the image
$user->image_url = $image_url;
$user->save();
}
}
View
Make sure to specify multipart/form-data
in the <form>
tag.
<form
method="post"
action="{{ route('profile.update') }}"
enctype="multipart/form-data"
>
@csrf
<input type="file" name="image" />
<button>Submit</button>
</form>
Confirming the Image is Saved in the Column and Storage Directory
Check the users
table and ensure that the image_url
column contains a path like:
user_profile_image/T5dNZzqtEUTu00FtkXvzU89n8vCDz8D0mkgZdMdp.png
Also, verify that the image file is saved at:
/storage/app/public/user_profile_image/T5dNZzqtEUTu00FtkXvzU89n8vCDz8D0mkgZdMdp.png
Displaying the Saved Image
Example:
<img src="{{ asset('storage/'.$user->image_url) }}" />
Alternative Methods
Another option is to use cloud storage services.
The main advantages are:
- Unlimited storage capacity, reducing issues related to data volume.
- Easier security configurations.
The disadvantage is the pay-as-you-go pricing model, which can become costly with large file volumes.
Examples include AWS S3 and Azure Storage (Blob).