Single and multiple Image uploading in Laravel 7 is not a difficult task in comparison to a core PHP. Laravel 7 provides the predefined functions for validating the image. Therefore, before uploading any image to the server, you can validate if the image has passed the validation criteria. In this post, I will guide you in the Laravel 7 image upload. After releasing Laravel 7, the security patches and bugs are fixed. Also, some new features have been added. In our last tutorial of Laravel 7, I have shown you a basic CRUD Application in Laravel 7 also, I have explained the new features. In this post, I am not going to dive into the detail of Laravel 7 features. So, let’s start with the Laravel 7 file upload tutorial.
Prerequisites
I hope you will have the required system criteria to create a new application in Laravel 7. But, if not, then please install the following tools. So that you can create and serve the Laravel 7 application.
- PHP >= 7.2.5
- MySQL > 5
- Apache/Nginx Server
- VS Code Editor (Optional)
- Composer
So, here I am going to create a new setup of Laravel using the composer.
Create a Project For Laravel 7 Image Upload
For creating a new application in Laravel 7, just enter the below command in the command prompt.
composer create-project --prefer-dist laravel/laravel laravel-7-image-upload
After hitting the above command, it will create a new project folder and in that folder, it will install the required dependencies and libraries.
Create and Configure Database
Open MySQL database, I am using the command line. So, just create a database there.
CREATE DATABASE laravel7_image_upload;
After creating the database, just configure it inside the project. To add the database configuration in the Laravel project, you will need to add the below credentials in .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel7_image_upload;
DB_USERNAME=root
DB_PASSWORD=root
Replace your database username and password if you have changed.
Create a Model and Migration
I will create a Model for File and a migration file that will be associated with this Model. The migration will create the table schema for the database. Here, I am going to guide you on Laravel 7 image upload. So, for this project, we required one Model and migration. Let’s create it
php artisan make:model File --migration
This will generate a model named File.php also, it will generate a migration file inside the database->migrations. The new migration file will be added there create_files_table.php
Now, change the table schema for the files table. Here, I have added a field named image_name.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFilesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('files', function (Blueprint $table) {
$table->id();
$table->string("image_name");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('files');
}
}
Now, we will migrate the table so that it will generate the schema of the files table in the database.
Migrate Tables in Laravel 7 Image Upload
After creating the table schema, we will need to migrate it so that it will generate the columns inside the table.
php artisan migrate
The above command will migrate all the tables. Here, we need only files_table. So the rest is optional. You can delete them all.
Add Fillable Data in the Model
For the Laravel 7 image upload, we will have to assign the field that we are going to insert into the database table. That means, after uploading the image in the folder, the file name will be inserted into the table. Therefore, we will be requiring to specify the fillable data.
Open the File.php file that will be inside the app folder. Now, add the below lines there.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
protected $fillable = [
"image_name"
];
}
Once, you are done, let’s create a controller in which we will be creating a function for image upload.
Create a Controller For Laravel 7 File Upload
I will create a controller for specifying the functionality for the Laravel 7 image upload. So open the terminal and hit the command to create a new controller there.
php artisan make:controller ImageUploadController
The above command will create a controller.
In the controller, just add the below functions. In the first function, I have returned a view. I will create a view in the next step and in that, I will create a form.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\File;
class ImageUploadController extends Controller
{
public function index() {
return view("index");
}
// upload image
public function imageUpload(Request $request) {
// file validation
$validator = $request->validate([
'images' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
// if validation success
$images = array();
if($files = $request->file('images')) {
foreach($files as $file) {
$name = time().'.'.$file->getClientOriginalExtension();
$destinationPath = public_path('/uploads');
if($file->move($destinationPath, $name)) {
$images[] = $name;
$saveResult = File::create(['image_name' => $name]);
}
}
return back()->with("success", "File uploaded successfully");
}
}
}
In the second function imageUpload(), I have read the multiple images. Then, I have used a validation rule to check whether the file type is an image or not. Also, I have checked the file size. So, all the required validation can be used here. Now, we’ll create a view from which I will be submitting the form with files.
Create a View For Multiple Image Upload
For Laravel 7 image upload, we’ll require one view. So, create a new view in the resource folder. Here, I have created a view named index.blade.php. You can add the below code there.
<!doctype html>
<html lang="en">
<head>
<title>Multiple Image Upload in Laravel 7 </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container mt-5 pt-5">
<form action="{{url('upload-proceed')}}" method="post" enctype="multipart/form-data">
@csrf
<div class="row">
<div class="col-xl-6 col-lg-6 col-12 m-auto">
<div class="card shadow">
@if(Session::has('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
{{Session::get("success")}}
</div>
@elseif(Session::has('failed'))
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
{{Session::get("failed")}}
</div>
@endif
<div class="card-header">
<h5 class="card-title"> Laravel 7 Multiple Image Upload </h5>
</div>
<div class="card-body">
<div class="form-group">
<label for="file"> Image <span class="text-danger">*</span> </label>
<input type="file" name="images[]" multiple class="form-control">
{!!$errors->first("images", "<small class='text-danger'>:message</small>") !!}
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Upload </button>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
In the above snippet, I have added an input type file with attribute multiple. Here, we are uploading multiple images that’s why I have specified multiple. This will allow us to upload multiple images. As we know, we cannot assign more that one value in a single variable. But an array variable can have multiple values. So, here I have created the file name as an array.
Create Routes For Multiple Image Upload
According to the controller functions I have created two web routes inside the web.php file. Add these routes there.
Route::get("image-upload", "ImageUploadController@index");
Route::post("upload-proceed", "ImageUploadController@imageUpload");
After adding the routes, let’s run the application. So as per the validation rules, the image file is required. It won’t allow you to submit the form without submitting the image.
Now, I try to upload any pdf file through this form.
When I clicked on the upload button, I got an error of file type. That is the file must be an image.
In the last test case, I have selected valid multiple images.
Now, after clicking on the upload button, I got the success message.
As a result, you can see the multiple images have been uploaded. Also, the images name have been inserted into the database table.
Leave a Reply