Performing a file upload can range from a user uploading pictures alongside articles, updating their profile picture, or sending documents. This is a crucial aspect of a web application, and Laravel makes it very easy.
$path = $request->file('avatar')->storeAs(
'avatars', $request->user()->id
);
The storeAs()
method receives two parameters:
The path (the directory you wish to put the file).
The file name(in our case, we use the user id).
In the syntax above, we call the storeAs()
method on the $request->file()
, which receives the file from the form. Then, we chain it with the storeAs()
method.
storeAs()
, as explained in the parameters section, receives two parameters. The first one is the name of the directory/folder in your application that you want to put the file in, and the second is the name you want to store the file as.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class UserAvatarController extends Controller
{
public function update(Request $request)
{
$path = $request->file('avatar')->storeAs('avatars',$request->user()->id);
return $path;
}
}
The above example shows how we store a file avatar
to the avatars directory in our application and save the file name as the user id. We finally return the $path
, which you can store into your database if you choose to do so.