In Laravel 6 the file upload is much more secure than the normal file upload in a PHP script. Laravel file upload provides the proper validation before uploading the files. Basically, in the file upload concept, Laravel moves files from the tmp directory to the public directory of the project folder, which is accessible by anyone. The files that are being uploaded can be renamed before moving to the public path in Laravel. In the previous tutorial, I showed you how to work with the database using the CRUD Application Tutorial in Laravel 6. Today, I’m here with the Laravel file upload tutorial to show you the Laravel upload file to storage.
Prerequisites
Before starting the tutorial, I am assuming that you have the composer installed in your system. You must have the PHP >= 7.2.0 version and MySQL database 8. I recommend to you MySQL 8 for Laravel 6.
Laravel File Upload
I will start with a new project for Laravel to upload files to storage. Therefore, open the command prompt or terminal and create a new Laravel 6 file upload project using the composer command.
composer create-project --prefer-dist laravel/laravel image-upload-app
Recommended: Laravel 6 User Registration and Login with Auth
Create Database and Configuration
For the database, I recommend you use MySQL 8. Because XAMPP has the default version of MySQL 8 which is not the latest.
Open MySQL 8 Command line or you can use MySQL Workbench too. Then log in with your password. Now, create a new database. In my case, I have created my database with the name laravel_file_upload.
CREATE DATABASE laravel_file_upload;
Now, use this database to check the tables.
USE laravel_file_upload;
show tables;
Currently, there are no tables inside this database because we’ll add it through the migration.
Recommended: How to Implement jQuery DataTable in PHP with MySQL
Once, you have created the database. Navigate to the Laravel 6 file upload project folder and configure the database credentials in the .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_file_upload
DB_USERNAME=root
DB_PASSWORD=root
Replace the above details with yours.
Recommended: Check Live Email Availability in PHP Using jQuery and AJAX
Add Front End Dependencies
Laravel provides the design dependencies with npm. So, we need to install it inside the project. Type the below command in the terminal.
npm install
It will take a while to add the required packages in your project.
Recommended: Drag and Drop Multiple File Upload in PHP Using Dropzone JS
After adding these packages to your project we’ll need to compile these files. So that it will create the necessary files for the development.
Run the below command in the terminal.
npm run dev
The above command will run the development file inside the project. And it will add the css and js folder inside the public folder of your project. In the css folder, there will be a file named app.css and similarly, in the js folder, there will be a file named app.js file.
Create Model and Migration
I will use the eloquent model class in Laravel 6 for the file upload. So first of all, create a Model and the migration file for the table. Laravel contains the migration of each table which is going to be created inside the database. This maintains the version of the tables which has been altered.
Enter the below command for creating the model and the migration table.
php artisan make:model File --migration
When you will run the above command, it will create a model with name File. And also, it will create a migration file in the database folder.
Recommended: How to Upload Multiple Images in Laravel 6 with Validation
In the migration folder, there will be some default migrations for the users. At this time, I am not going to work on the User module in the project so no need to carry these migration files. So, delete them for now.
Open the create_files_table.php migration file and change the schema with this.
public function up()
{
Schema::create('files', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('filename');
$table->timestamps();
});
}
Add Fillable Data in the Model
Open the model named File.php which is inside the App\File.php and add the below code. Here, I am assigning the field name which will be inserted into the table after the file upload.
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
protected $fillable = ['filename'];
}
Migrate Table in the Database
Next, you’ll need to migrate the migration file through the command so that it can create a table inside your database with the same schema.
php artisan migrate
Open the database and check the table schema after the migration successful.
Recommended: File Upload in PHP Using jQuery and AJAX
Create Controller For Laravel 6 File Upload
Now, you will need to create a Controller that will manage every business logic of this file upload tutorial. Here, I’m creating FileController with a resource that will add the default methods inside the controller.
Type the below command to create a controller.
php artisan make:controller FileController --resource
Create Route in Laravel 6
For creating the route for the webpages navigate to the routes folder. You will find the web.php file there. Now, add the resource route as shown below.
Route::resource('file', 'FileController');
The Laravel provides the resource route for the resource controller. Therefore, in this case, we don’t need to specify the method type which is get, post, put, patch, and delete. It will detect automatically all types of routes.
Create View in Laravel 6 For File Upload
Navigate to the resources folder in the project, you will find the views folder. All the views will reside here. Laravel uses a blade template engine for creating the views.
So here, I am going to create the following blade files –
- layout.blade.php
- create.blade.php
In the layout.blade.php file, I will create a master template that can be extendable in other blade files.
Paste the below blade snippet in the layout.blade.php file.
layout.blade.php
<!doctype html>
<html lang="en">
<head>
<title> Laravel 6 File Upload</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">
</head>
<body>
@yield('content')
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" crossorigin="anonymous"></script>
</body>
</html>
Now, I will extend the above blade file in the create.blade.php file. So that the CSS and js library will be included in this file. Also, using the @yield() function we can add the HTML content dynamically.
create.blade.php
@extends('layout')
@section('content')
<div class="container mt-5">
<form action="{{ route('file.store') }}" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<div class="card shadow">
<div class="card-header bg-info text-white">
<div class="card-title ">
<h4> Laravel 6 File Upload </h4>
</div>
</div>
<div class="card-body">
<!-- print success message after file upload -->
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
<div class="form-group" {{ $errors->has('filename') ? 'has-error' : '' }}>
<label for="filename"></label>
<input type="file" name="filename" id="filename" class="form-control">
<span class="text-danger"> {{ $errors->first('filename') }}</span>
</div>
</div>
<div class="card-footer">
<div class="form-group">
<button type="submit" class="btn btn-success btn-md"> Upload </button>
</div>
{{ csrf_field() }}
</div>
</div>
</div>
</div>
</div>
@endsection
Load View in the Controller
Once, the above blade file has been created, it’s time to load it in the controller. So, I will create this blade file inside the create() method of the FileController.
public function create()
{
return view('create');
}
Recommended: Laravel 6 RESTful APIs with Passport Authentication
Image Validation and File Upload
When the view sends data to the controller function, in the resource route it will be sent to the store() method which will handle the request. So, here I am going to validate the image file first. Basically, we know that every file has its extension. Therefore, to validate the image file I will check the file extension that is being uploaded.
In Laravel 6, we will use the Validator class that is used to validate the inputs. Replace the below code with your store() method inside the FileController.
public function store(Request $request)
{
// file validation
$validator = Validator::make($request->all(),
['filename' => 'required|mimes:jpeg,png,jpg,bmp|max:2048']);
// if validation fails
if($validator->fails()) {
return back()->withErrors($validator->errors());
}
// if validation success
if($file = $request->file('filename')) {
$name = time().time().'.'.$file->getClientOriginalExtension();
$target_path = public_path('/uploads/');
if($file->move($target_path, $name)) {
// save file name in the database
$file = File::create(['filename' => $name]);
return back()->with("success", "File uploaded successfully");
}
}
}
If I choose other files rather than image then it will return the file type error. Here the filename is the name of the input type file that’s why it is showing the validation error for that input field.
Create a folder named uploads inside the public folder of your project. After the file validation success, the file will be uploaded into the target directory which is defined in the above code.
Also, the file name has been saved into the database table.
Display Image in View
For displaying images from the database table, I will use eloquent. So, it will make easy for us to write the SQL Queries. Paste the below code in the index() of the FileController.
public function index()
{
// fetch all the images
$files = File::all();
return view('index', compact('files'));
}
We have already created the index.blade.php file. Now, I will load all the images in this blade file. For displaying images, I have created a layout for thumbnail display. So, paste the below blade file.
index.blade.php
@extends('layout')
@section('content')
<div class="container mt-5 border p-3">
<div class="row pb-5">
<div class="col-xl-12">
<a href=" {{ route('file.create') }} " class="btn btn-success btn-sm float-right"> Add More </a>
</div>
</div>
<div class="row">
@foreach($files as $file)
<div class="col-xl-3 col-lg-3 col-md-6 col-sm-6 col-6 m-auto p-2">
<div class="card shadow">
<div class="card-body">
<img src="/uploads/{{ $file->filename }} " class="img-fluid img-thumbnails">
</div>
</div>
</div>
@endforeach
</div>
</div>
Save and run the project to see the result. Here, the images are displaying in the thumbnail view.
Conclusion
Laravel handles the files and images upload with proper validations. In this post, we have done the validations and file uploading to the server successfully. I hope, you will find helpful in this tutorial. Implement this file upload example in your actual projects. If you want to contact regarding the query of this post, then write your query in the comment section.
Rizky Satria Wibowo says
hi i want input multiple file from laravel 6
Umesh Rana says
You will have to create an array of input type file. Just follow this link –
How to Upload Multiple Images in Laravel 6
Jorge says
Hello Umesh, thanks for share this post, it was very usefully for me. I’m a beginner in Laravel, how can I do to show the view index?