There are several laravel and third party features that can solve this issue for you, for a better exponation, let's solve a common problem, uploading an user avatar:
you have the following form:
<form method="POST" action="/avatar" accept-charset="UTF-8" enctype="multipart/form-data">
{{ csrf_field() }}
<div>
<input name="avatar" type="file">
</div>
<div class="margin-top-10">
<input type="submit" class="btn green" value="Submit" />
</div>
that is the form to upload a file, note that you need to put accept-charset
and enctype
attributes in order to the file field works with your backend. After this, you have to make your controller to upload the avatar, imagine you have the ProfileController
class, simply as this action:
public function set_profile_picture(Request $request) {
$user = $request->user();
if (!$request->hasFile('avatar')) {
Flash::error('Avatar not found');
return redirect('/profile');
}
$path = $request->file('avatar')->store('avatars');
$user->avatar = $path;
$user->save();
return redirect('/profile');
}
Check that you can get the file from the frontend form by using $request->file(avatar)
, with that done, you need to define the route: Route::post('/avatar', 'Auth\ProfileController@set_profile_picture');
And finally, you need to make another thing to show the picture uploaded, you have to choices, storing the file in the server is made by the Storage
Facade in Laravel, so, you will find out that you cannot give public access to these files because they are in a folder named storage
, you can always make a symbolic link to the folder containing the avatars to have access to them in the public
folder where you have the front controller and all those stuffs, but if you are using some VCS like git, this symlink could bring you problems in the future, the most secure way to do this is to define another action in your controllers to access a private file in your storage, the following is the better way to do this:
Route::get('avatars/{filename}', function ($filename) {
$path = storage_path() . '/app/avatars/' . $filename;
if(!File::exists($path)) abort(404);
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
You can find more information about the Storage Facade in the laravel official documentation, to unlink a file is simple Storage::Delete('/path/to/file.jpg');
Hope it helps you this little exponation, bests! ;)