Emz
Emz

Reputation: 542

Handling File Upload in Laravel's Controller

How can I use the following PHP $_FILES using Laravel's Request object? (i'm using Laravel 5.3)

$_FILES["FileInput"]
$_FILES["FileInput"]["size"]
$_FILES['FileInput']['type']
$_FILES['FileInput']['name']
$_FILES['FileInput']['tmp_name']

Anyone has an idea working this before that would be very much appreciated. Thank you!

Upvotes: 15

Views: 53889

Answers (1)

anon
anon

Reputation:

From the Laravel docs

Retrieving Uploaded Files

You may access uploaded files from a Illuminate\Http\Request instance using the file method or using dynamic properties. The file method returns an instance of the Illuminate\Http\UploadedFile class, which extends the PHP SplFileInfo class and provides a variety of methods for interacting with the file:

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

$file = $request->photo;

You may determine if a file is present on the request using the hasFile method:

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

Validating Successful Uploads

In addition to checking if the file is present, you may verify that there were no problems uploading the file via the isValid method:

if ($request->file('photo')->isValid()) {
    //
}

File Paths & Extensions

The UploadedFile class also contains methods for accessing the file's fully-qualified path and its extension. The extension method will attempt to guess the file's extension based on its contents. This extension may be different from the extension that was supplied by the client:

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

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

To get File name

$filename= $request->photo->getClientOriginalName();

Example

$file = $request->file('photo');
   
//File Name
$file->getClientOriginalName();

//Display File Extension
$file->getClientOriginalExtension();

//Display File Real Path
$file->getRealPath();

//Display File Size
$file->getSize();

//Display File Mime Type
$file->getMimeType();
  
//Move Uploaded File
$destinationPath = 'uploads';
$file->move($destinationPath,$file->getClientOriginalName());

Upvotes: 54

Related Questions