This article is about Laravel Image Upload Validation Tutorial Example.
I will guide you how to implement some validations before uploading image into laravel project.
Validations like image size, different types of image format (png, jpg, jpeg etc.) etc. are covered.
We will also print the errors if validations are not fulfilled perfectly.
First of all, see the below youtube video to show validations.
Step 1. New project and MySQL Database
First of all, write down the below command in terminal
laravel new laraimagevalidation
- This line will make a fresh new laravel project whose name will be “laraimagevalidation“
- Now open up your MySQL database administration tool. I am using sequel pro. Process for making new database is same for other tools also.
- Just create a new database into the database administration tool. Set the name of the database as “laraImageUpload“
Now in your editor, open .env file of your laravel project.
In this .env file, you need to modify the below code lines
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laraImageUpload DB_USERNAME=root DB_PASSWORD=
- Update all the above fields as per your configuration.
Once you do this, you have connected your laravel project with MySQL database.
Step 2. New Table in Database
Time to create a table in our database.
Fire up the following command in your terminal
php artisan make:migration create_cars_table
- Above line will create a new migration file.
- Go to app->database->migrations folder. Inside migrations folder, you will find a new file named “time_create_cars_table.php”
New file “time_create_cars_table.php” should contain the below source code
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCarsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('cars', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('path'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('cars'); } }
- Look at the up() function. This function has four lines.
- Each line is referring to a column name and type of the table.
- First line will create “id” column and its type is auto increment and integer.
- Second one will make column “name” and its type is string.
- Third is making “path” and last one is making timestamps.
Finally, trigger the below command
php artisan migrate
After the successful implementation of above command, you will find a table “Cars” in your database.
Step 3. Model Plus Control
Now we need to make one model class and one controller class.
For this, run the below command first
php artisan make:controller CarsController -r -m Car
- Above command will try to make a controller class. For this, it will check there is a model class or not. We have not created model yet so it will ask you if you want to create model or not.
Say yes for making model. See the below lines
php artisan make:controller CarsController -r -m Car A App\Car model does not exist. Do you want to generate it? (yes/no) [yes]: > yes Model created successfully. Controller created successfully.
- So, after this much of terminal work, system have created a controller class “CarsController.php” and a model class “Car.php“
You need to add one line in your “Car.php” file. Full source for “Car.php” is as the below
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Car extends Model { // public $table = "cars"; }
- Just one lie in class and that’s all.
- Now navigate to app->Http->Controllers->CarsController.php
Write down the following source snippet in CarsController.php
<?php namespace App\Http\Controllers; use App\Car; use Illuminate\Http\Request; class CarsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { //dd('here'); return view('uploadfile'); } public function storeCar(Request $request) { $this->validate($request, [ 'fileToUpload' => 'required|image|mimes:jpg,jpeg,png,gif|max:2048' ]); $destinationPath = public_path('/images'); $image = $request->file('fileToUpload'); $input['imagename'] = time().'.'.$image->getClientOriginalExtension(); $image->move($destinationPath, $input['imagename']); $dbPath = $destinationPath. '/'.$input['imagename']; //dd($dbPath); $car = new Car(); $car->name = request('imagename'); $car->path = $dbPath; $car->save(); //return view('uploadfile'); return back()->with('success', 'Image Uploaded Successfully With Validation')->with('path', $input['imagename']); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param \App\Car $car * @return \Illuminate\Http\Response */ public function show(Car $car) { // } /** * Show the form for editing the specified resource. * * @param \App\Car $car * @return \Illuminate\Http\Response */ public function edit(Car $car) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Car $car * @return \Illuminate\Http\Response */ public function update(Request $request, Car $car) { // } /** * Remove the specified resource from storage. * * @param \App\Car $car * @return \Illuminate\Http\Response */ public function destroy(Car $car) { // } }
I will explain functions of above file later.
Step 4. Web.php a Route File
Now go to app->routes->web.php file which is holding all the routes of laravel project.
Add the following source snippet in this file.
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('uploadfile','CarsController@index'); Route::post('uploadsql','CarsController@storeCar');
- Two routes are there.
- A route /uploadfile will call the index function from controller.
- Second route will execute storeCar function from controller.
Making Images Folder
Inside public folder, make a new folder and give it a name “images“.
We will upload our images in this newly created “images” folder only.
Step 5. View Blade Making
Under resources->views directory, make a new file called “uploadfile.blade.php”
In this file, write down the following source snippet
<!DOCTYPE html> <html> <head> <title>File Uploading in Laravel</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <br /> <div class="container"> <h3 >Upload Image Validation Laravel</h3> <br /> @if (count($errors) > 0) <div class="alert alert-danger"> Upload Validation Error<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif @if ($message = Session::get('success')) <div class="alert alert-success alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $message }}</strong> </div> <img src="/images/{{ Session::get('path') }}" width="300" /> @endif <form method="POST" action="/uploadsql" enctype="multipart/form-data"> @csrf <div class="form-group"> <label class="lable" for="name">Car Name </label> <div class="control"> <input type="text" class="form-control" name="imagename" placeholder="Title" value="" required> </div> </div> <div class="form-group"> <div class="control"> <input type="file" class="form-control" name="fileToUpload" aria-describedby="fileHelp"> </div> </div> <div class="form-group"> <div class="control"> <button type="submit" class="btn btn-primary">Upload Car</button> </div> </div> </form> </body> </html>
Understanding above blade
First, consider the below code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
- Above three lines are integrating the classes of jQuery and bootstrap in our blade file.
- After this, we can use these packages to make our view file more beautiful.
See the below lines
@if (count($errors) > 0) <div class="alert alert-danger"> Upload Validation Error<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif @if ($message = Session::get('success')) <div class="alert alert-success alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $message }}</strong> </div> <img src="/images/{{ Session::get('path') }}" width="300" /> @endif
- First if condition will check if there is any error or not. If there is error then it will iterate one foreach loop.
- During every iteration of loop, system will print the error message inside red box. Errors are generated when any validation of image got wrong.
- There is also a second if condition which will check if message has status as a “success“.
- If status is success then it will print the success message in green box.
- In the next line, system will also show uploaded image.
Below code is for form creation.
<form method="POST" action="/uploadsql" enctype="multipart/form-data"> @csrf <div class="form-group"> <label class="lable" for="name">Car Name </label> <div class="control"> <input type="text" class="form-control" name="imagename" placeholder="Title" value="" required> </div> </div> <div class="form-group"> <div class="control"> <input type="file" class="form-control" name="fileToUpload" aria-describedby="fileHelp"> </div> </div> <div class="form-group"> <div class="control"> <button type="submit" class="btn btn-primary">Upload Car</button> </div> </div> </form>
- This form will hit the /uploadsql URL when it is submitted.
- This form includes one text filed and two buttons.
- User will enter the name of the car in the text field.
- Choose File button will open one pop up screen. User can select the image file from this pop up window.
- After selecting the file, user clicks the “Upload Car” button and system will start the uploadation process.
- Actually, system will call the storeCar() function from controller file when user clicks the “Upload Car” button.
Following is the storeCar() function code lines
public function storeCar(Request $request) { $this->validate($request, [ 'fileToUpload' => 'required|image|mimes:jpg,jpeg,png,gif|max:2048' ]); $destinationPath = public_path('/images'); $image = $request->file('fileToUpload'); $input['imagename'] = time().'.'.$image->getClientOriginalExtension(); $image->move($destinationPath, $input['imagename']); $dbPath = $destinationPath. '/'.$input['imagename']; //dd($dbPath); $car = new Car(); $car->name = request('imagename'); $car->path = $dbPath; $car->save(); //return view('uploadfile'); return back()->with('success', 'Image Uploaded Successfully With Validation')->with('path', $input['imagename']); }
- First few lines will check the validations of selected images.
- It will allow the types of files as “jpg,jpeg,png and gif“. Other than these file types will be discarded.
Second validation is the size of the image. Maximum size of image should be 2048 kb. Larger than this size will also be discarded.
- $destinationPath will get the path to the images folder.
- $request variable will help to get the original file into $image.
- $input[‘imagename’] will hold the value of current time and we will use this variable as the name of the uploaded file.
- $dbPath represent the value which system will add into the path column in database.
- Finally, the $car variable will use the save() method to input values into the database.
- Now run your project using “php artisan serve” command.