Laravel File Upload Validation Example With MySQL Database

install laravel, laravel install mysql, laravel get all data records, insert form data into database using laravel, laravel crud example, laravel custom 404, laravel registration and login, laravel 5.7 email verification, laravel 5.8 crud, laravel email verification, laravel facebook login, laravel google login, laravel file upload, laravel image upload, laravel image upload validation, laravel file upload validation, laravel form validation, laravel one to one relationship

This writings is about Laravel File Upload Validation Example With MySQL Database.

I will show you how to upload file with validation in laravel.

We will cover validations like various types of file and file size.

After successful upload of file to any folder, we will enter name and path of the uploaded file into the MySQL database.

So first check the below output of this example.

Now follow all the below steps to make above tutorial.

Step 1. Database and Project Creation

First of all, trigger the below command in your terminal

laravel new larafilevalidation
  • This line will make a new laravel project. Name of the laravel project would be “larafilevalidation
  • Now let us open our database administration tools. Mine is sequel pro.
  • If you have other than sequel pro like phpMyAdmin or any else then it is also ok. We just need to create a new database manually in our database administration tool.
  • Set the name of the database as “larafileupload

So now we have brand new laravel project as well as MySQL database. Now go to your editor and open .env file of your project.

You need to change the below lines of .env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=larafileupload
DB_USERNAME=root
DB_PASSWORD=
  • As per your machine configuration, update the above fields.

Now you have connected your laravel project with MySQL database.

Step 2. New migrations and table

To create a new table in database, we need to make a new migration file first.

So fire up the following command

php artisan make:migration create_cars_table
  • This command will make a new migration file under app->database->migrations folder.
  • Name of this migration file would be something like “time_create_cars_table.php”

Write down the below source lines in this “time_create_cars_table.php” file

<?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');
    }
}
  • up() function in the above file is the main part.
  • It consist the name and types of the columns on the Cars table.
  • Four columns are there : id, name, path and timestamp.

Run the following command

php artisan migrate

After the successful implementation of above command, you will find a table “Cars” in your database.

Step 3. Making Controller and Model File

Run the following command in terminal.

php artisan make:controller CarsController -r -m Car
  • This command will try to create a new migration file. For this, it will check if there is a model class called “Cars.php” is created or not.
  • We do not have created any model class so it will ask you whether you want to make a new class or not. Write “yes” as an answer.

See the below terminal 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.
  • After all of these terminal tasks, system should have created a controller file whose name is “CarsController.php” and a model class with name Cars.php

Now open the app->Cars.php file. Add the below code in it

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    //
    public $table = "cars";
}
  • I have added just one line in this php file.
  • Now go to app->Http->Controllers->CarsController.php file.

Write down the following source lines in this file.

<?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|mimes:doc,docx,pdf|max:2048'
           ]);
        
        $destinationPath = public_path('/uploadedfiles');
        $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', 'File 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)
    {
        //
    }
}

This file have several functions which I will explain later.

Step 4. Two Routes

First of all, open app->web.php file.  Add the following source lines 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');
  • As you can see that I have added two routes manually.
  • First one is hitting the /uploadfile URL and it will call index() function from CarsController file.
  • Second line will execute storeCar() function when it hit /uploadsql URL.

Creating uploadfiles Folder

Let us create a folder where we will store the uploaded files.

Inside public folder, create a new folder and give it a name like “uploadfiles

Step 5. View Files

Under resources->views directory, make a new file called “uploadfile.blade.php

Inside this file, add the following code 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>
   
   @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 File</button>
 
            </div>
 
        </div>
 
    </form> 
 
    </body>
</html>

Deeper Look

Let us deeply see what above code snippet is doing.

First of all, 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>
  • These three lines are integrating jQuery and bootstrap in our blade file.
  • Using these libraries, we can made our view file more user friendly.

Now see the below

 @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
  • Above lines are checking one if condition for any errors. When this condition is true that means some validation errors are raised.
  • Then there is one foreach loop. During every iteration of this foreach loop, system will print one error message in red box.
  • Thus, every error will be printed inside rex box.

Now see the below codes

 @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>
   
   @endif
  • Here, compiler is checking for success message. If it found then if condition will be true.
  • Then it will simply print the success message inside a green box.

Finally, below is the last snippet

 <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 File</button>
 
            </div>
 
        </div>
 
    </form>
  • Above is making a form which is able to take file inputs with multipart.
  • This form includes one text field and two buttons (Choose File and Upload File) .
  • When the user clicks the Choose File button, system will open one pop up window.
  • This window allows the user to select any file from his computer.
  • After selecting a file and inputing its name in text field, he will click on Upload File button.
  • When he clicks Upload File button, system will hit /uploadsql URL and it will upload the selected file if file has satisfied all the validations.
  • System will call storeCar() function when clicks Upload File button.

Below is the source snippet for storeCar() function.

 public function storeCar(Request $request)
    {
 
        $this->validate($request, [
            'fileToUpload'  => 'required|mimes:doc,docx,pdf|max:2048'
           ]);
        
        $destinationPath = public_path('/uploadedfiles');
        $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', 'File Uploaded Successfully With Validation')->with('path', $input['imagename']);
    }
  • First three lines are defining validations. Type of file must be doc,docx or pdf and it’s size must be less than 2048 KBs.
  • $destinationPath will get the path to the uploadedfiles folder.
  • $image will get the all data of uploaded file.
  • A time stamp will be stored inside $input[‘imagename’] variable.
  • $image->move …. line will save the file inside uploadedfiles folder.

See the below lines

 $dbPath = $destinationPath. '/'.$input['imagename'];
        //dd($dbPath);
        $car = new Car();
        $car->name = request('imagename');
        $car->path = $dbPath;
 
        $car->save();

These lines will insert the file name and path into the database.

Download Code For Laravel File Upload Validation

Github Path to full source code of this tutorial.