Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling File Upload in Laravel's Controller

Tags:

php

laravel

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!

like image 340
Emz Avatar asked Oct 14 '16 02:10

Emz


1 Answers

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();

Ref:https://laravel.com/docs/5.3/requests

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());
like image 70
Vision Coderz Avatar answered Oct 11 '22 21:10

Vision Coderz