In this article lets get our hands dirty by working on File Upload In PHP Laravel.
We will cover the following topics
- Laravel Installation
- Local Server Starting
- Web Routes And Controllers
- HTML Form For File Uploading
- Handle File Upload In Controller
- Complete Controller Code
Step 1 - Laravel Installation
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
.
Step 2 - Local Server
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.
Step 3 - Web Routes And Controllers
I have created the FileUploadsController to handle redirects to view page and after uploading from view page mange the file upload.
Controller - FileUploadsController
php artisan make:controller FileUploadsController
web.php
Route::get('/file-uploads/create', 'FileUploadsController@create');
Route::post('/file-uploads', 'FileUploadsController@store');
Step 4 - HTML Form For File Uploading
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
Step 5 - Handle File Upload In Controller
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
/** Validation - You can use any other file mime types like SVG, */
request()->validate([
'attachment' => 'required|mimes:png,jpg,jpeg'
]);
Check If Form Request Has Attachment (I usually prefer first one)
if(request()->hasFile('attachment')) {
}
OR
if(request()->has('attachment')) {
}
Laravel File Helper Methods
/** 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 File Name - You can use any other way too
/** 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
]);
Public Path - Not In Storage Path
/** Instead of storage I will demo you storing in PUBLIC path same as that of assets folder */
$uploadPath = public_path() . '/uploads/attachments/';
Specifying A Disk (Laravel Docs)
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'
);
Step 6 - Complete Controller Code
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';
}
}
}
Conclusion
Hope you enjoyed the article. Please share it with your friends.
Random Articles For You
Make Laravel Controllers Slim By Skimming Form Validation Request
Free SSL Certificate With Lets Encrypt/Certbot In Linux (Single / Multiple Domains)
Multiple GIT Key Pairs Or Account In The Same Computer
Laravel Clear Cache Of Route, View, Config Command
Create Custom 404 Page In Laravel
Send Email In PHP With PHPMailer
Generate Sitemap in PHP Laravel
Relationship Table Data With Route Model Binding In Laravel
Detect AdBlocker With Javascript And Increase Website Ads Revenue
composer.json v/s composer.lock