
Good content takes time and effort to come up with.
Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.
Hola Amigos! In this article lets get our hands dirty by working on File Upload In PHP Laravel.
We will cover the following topics
If you already have the Laravel application skip to Step 2 else let's install the Laravel application with composer using the following command
composer create-project --prefer-dist laravel/laravel blog
The above command creates a new Laravel project with a name blog
.
For the sake of demonstration I will keep the settings very simple and to run our project I will start the PHP built-in server with the help of artisan command as follows
php artisan serve
You will be able to see similar to the following output.
Laravel development server started: <http://127.0.0.1:8000>
Now you can run your application by running http://localhost:8000
or http://127.0.0.1:8000
from your web browser.
I have created the FileUploadsController to handle redirects to view page and after uploading from view page mange the file upload.
php artisan make:controller FileUploadsController
Route::get('/file-uploads/create', 'FileUploadsController@create');
Route::post('/file-uploads', 'FileUploadsController@store');
Let's see how our file uploading form looks like. For the sake of demonstration, I am just using only one field.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Upload</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<h2 class="text-primary">File Upload Demo</h2>
<form action="{{ url('file-uploads') }}" method="post" enctype="multipart/form-data">
@csrf
<div class="row">
<div class="col-md-12 form-group">
<label for="attachment"></label>
<input type="file" name="attachment" id="attachment" class="form:control">
</div>
</div>
<br>
<div class="row">
<div class="col-md-12 form-group">
<input type="submit" value="Upload File" class="btn btn-primary">
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Make sure not to skip enctype
attribute in your form opening tag
<form action="{{ url('file-uploads') }}" method="post" enctype="multipart/form-data">
If you now run the http://localhost:8000/file-uploads/create
URL in your browser you will be able to similar to the following output
In this step lets handle the file submitted from the above file. First let's see the full implementation then we will break down the code to understand.
public function store()
{
/** Validation */
request()->validate([
'attachment' => 'required|mimes:png,jpg,jpeg'
]);
/** Even request()->has('attachment') works */
if (request()->hasFile('attachment')) {
/** This is of type file */
$attachment = request()->file('attachment');
/** Laravel file helper methods */
$attachmentExtension = $attachment->getClientOriginalExtension();
$attachmentMimeType = $attachment->getClientMimeType();
$attachmentName = $attachment->getClientOriginalName();
$attachmentSize = $attachment->getClientSize();
/** New attachment name, v - milliseconds */
$attachmentNewName = 'attachment' . date('YmdHisv') . '.' . $attachmentExtension;
/** Instead of storage I will demo you storing in PUBLIC path same as that of assets folder */
$uploadPath = public_path() . '/uploads/attachments/';
/** Moving the uploaded path of public folder */
$attachment->move($uploadPath, $attachmentNewName);
/** You can store in database as follows make sure to fill the rest of the fields :) */
/*
Attachment::create([
'name' => $attachmentNewName
]);
*/
echo 'Upload completed';
}
}
Let's break down the above gigantic code
/** Validation - You can use any other file mime types like SVG, */
request()->validate([
'attachment' => 'required|mimes:png,jpg,jpeg'
]);
if(request()->hasFile('attachment')) {
}
OR
if(request()->has('attachment')) {
}
/** Laravel file helper methods */
$attachment->getClientOriginalExtension(); /** png */
$attachment->getClientMimeType(); /** image/png */
$attachment->getClientOriginalName(); /** testing.png */
$attachment->getClientSize(); /** 23422 */
With the help of the above file helpers you can check the size of the file, check the image extensions and do a lot of other validations as per your needs.
Tip: You can do this validations in require()->validate()
You can also use Intervention Image package to mange image related operations very easily.
/** New attachment name, v - milliseconds */
$attachmentNewName = 'attachment' . date('YmdHisv') . '.' . $attachmentExtension;
Other ways to generate unique id's are - time(), uniqid(), md5(time())
You can use this new attachment name to store in your database to display later in your view pages like the following
Note: The following is for the sake of demonstration, you may have different Model name and fields
Attachment::create([
'name' => $attachmentNewName
]);
/** Instead of storage I will demo you storing in PUBLIC path same as that of assets folder */
$uploadPath = public_path() . '/uploads/attachments/';
By default, this method will use your default disk. If you would like to specify another disk, pass the disk name as the second argument to the store method:
$path = $request->file('avatar')->store(
'avatars/'.$request->user()->id, 's3'
);
If you are using the storeAs method, you may pass the disk name as the third argument to the method:
$path = $request->file('avatar')->storeAs(
'avatars',
$request->user()->id,
's3'
);
Following is the complete code of the controller. Tried my best to explain in comments
class FileUploadsController extends Controller
{
public function create()
{
return view('file-uploads.create');
}
public function store()
{
/** Validation */
request()->validate([
'attachment' => 'required|mimes:png,jpg,jpeg'
]);
/** Even request()->has('attachment') works */
if (request()->hasFile('attachment')) {
/** This is of type file */
$attachment = request()->file('attachment');
/** Laravel file helper methods */
$attachmentExtension = $attachment->getClientOriginalExtension();
$attachmentMimeType = $attachment->getClientMimeType();
$attachmentName = $attachment->getClientOriginalName();
$attachmentSize = $attachment->getClientSize();
/** New attachment name, v - milliseconds */
$attachmentNewName = 'attachment' . date('YmdHisv') . '.' . $attachmentExtension;
/** Instead of storage I will demo you storing in PUBLIC path same as that of assets folder */
$uploadPath = public_path() . '/uploads/attachments/';
$attachment->move($uploadPath, $attachmentNewName);
echo 'Upload completed';
}
}
}
Hope you enjoyed the article. Please share it with your friends.
GitHub Login With PHP Laravel Socialite
Create A Composer Package? Test It Locally And Add To Packagist Repository
Simple Way To Create Resourceful API Controller In Laravel
Facebook Login With PHP Laravel Socialite
Localization In Laravel REST API
Resolve 404 Not Found In NGINX
Install Packages Parallel For Faster Development In Composer
SQLite Doesn't Support Dropping Foreign Keys in Laravel
Setup MAMP Virtual Hosts For Local PHP Development
Custom Validation Rules In PHP Laravel (Using Artisan Command)
Accessors And Mutators In PHP Laravel