Laravel Uploading Files

Retrieving Uploaded Files

We can access files from an Illuminate\Http\Request. By using the file method or using the dynamic properties.

The file method returns an instance of the Illuminate\Http\UploadedFile class that extends the PHP SplFileInfo class. It provides a several methods for interacting with the file

$file = $request->file('photo');
$file = $request->photo; 

We can specify if a file is present on the request by using the hasFile method

if ($request->hasFile('photo')) {
 //statement
 } 

Validating Successful Uploads

To check if the file is present, we have to verify that there was no problem in uploading the file with the help of the isValid method

If ($request->file(‘photo’)->isValid())
 {
 //statement
 } 

File Paths & Extensions

The UploadedFile class contains methods for accessing the file`s which have a fully-qualified path and its extension.

The extension method will try to guess the file`s extension based on its contents.

The extension can be different from the extension which was given by the client.

$path = $request->photo->path();
$extension = $request->photo->extension(); 

Storing Uploaded Files

The UploadedFile class has a store method by which we will move an uploaded file to one of our disks, which can be a location on our local filesystem or even a cloud storage location like Amazon S3.

The store method accepts the path where all the files are stored relative to the filesystem`s configured root directory.

This path does not contain a file name, a unique ID will automatically be generated to serve it as the file name.

The store method also accepts a second argument as an option for the name of the disk which is used to store the file.

The method will return the path of the file relative of the disk`s root.

$path = $request->photo->store(‘images’);
$path = $request->photo->store(‘images’, ‘s3’); 

If we do not want a file name to be generated automatically, then we can use the storeAs method that accepts the path, file name, and the disk name as its arguments

$path = $request->photo->storeAs('images', 'filename.jpg');
$path = $request->photo->storeAs('images', 'filename.jpg', 's3'); 



ADVERTISEMENT
ADVERTISEMENT