Laravel File Upload Tutorial Example Step By Step From Scratch

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

Welcome to Laravel File Upload Tutorial Example Step By Step From Scratch.

Table of Content

1. Laravel File Upload Tutorial Example Step By Step From Scratch

2. Laravel File Upload Validation Example With MySQL Database

1. Laravel File Upload Tutorial Example Step By Step From Scratch

In this tutorial, I will guide you to upload file in your laravel project.

We will get the file from user’s computer and then we will store it in our laravel project.

Along with file, we will also insert the details like name and path of the file into the MySQL database.

First of all, just look at the below video demonstration.

Step 1. Make a new Project and Database

Fire up the below command first,

laravel new larafileupload
  • Above command will make a new project named “larafileupload”

Now let us create a new database. I am using sequel pro as a database administration tool.

If you are using other tools like phpMyAdmin or else than don’t worry, process is same.

First of all, create a new database called “larafileupload”

Now come to your laravel project and open your .env file.

Inside this .env file, you need to change below details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=larafileupload
DB_USERNAME=root
DB_PASSWORD=
  • My username is root and password is empty. You should fill above fields as per your configuration.

After this, we have successfully connected our project with MySQL database.

Step 2. Making a Table in Database

After database, let us make a new table in this “larafileupload” database.

So in your terminal, run the following command

php artisan make:migration create_cars_table

This command will create a new migration file.

Navigate to app->database->migrations folder. Inside migrations folder, you will find a new file named “time_create_cars_table.php”

This file contains 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');
    }
}

I have changed the up() function in the above file.

All four lines in the up() function represents the name of the columns of the Cars table.

Now fire the below command

php artisan migrate
  • When this command triggers, system will create a new table named “Cars” in “larafileupload” database.

Step 3. Code for Model and Controller

Again we need to fire the below command

php artisan make:controller CarsController -r -m Car
  • Below command will try to create controller file. Before making controller it will check whether a model called “Car” is there or not.

Because model class do not exist, it will check whether you want to create model or not? write “yes” here. See the below

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, as per above lines, a controller class called “CarsController.php” and a model class called “Car.php” is created.

Now in your Car.php write down the below source snippet.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    //
    public $table = "cars";
}

I have just added one line in the above file.

  • Now go to app->Http->Controllers->CarsController.php

CarsController.php file should contain the following coding lines

<?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)
    {
        
        $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 Upload successful');
    }

    /**
     * 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 controller lines have several functions. I will explain all these functions later.

Step 4. Writing Routes

Now Navigate to app->routes->web.php file.

Source snippet for this file is as the below

<?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');

I have added below two lines which are defining custom routes.

Route::get('uploadfile','CarsController@index');
Route::post('uploadsql','CarsController@storeCar');

First line is defining one get route. It will access the index() function from CarsController.php file.

Second line is making post route which is referring storeCar() function.

Making Images Folder

Make a new folder inside public folder. Name of this new folder should be “images”

We will upload our files in this “images” folder.

Step 5. Blade File

Create a new blade file named “layout.blade.php” under resources->views file.

Add the following source lines in this “layout.blade.php” file.

</<!DOCTYPE html>
<html>
<head>
 
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.css">
    
</head>
 
<body>
 
    <div class="container">
        @yield('content')
    </div>    
 
</html>

Now create another blade file named “uploadfile.blade.php”

In this file, you need to add the below source snippet

@extends('layout')
 
@section('content')

    <br>
    @if (count($errors) > 0)
	<div class="alert alert-danger">
		<strong>Whoops!</strong> There were some problems with your input.<br><br>
		<ul>
			@foreach ($errors->all() as $error)
				<li>{{ $error }}</li>
			@endforeach
		</ul>
	</div>
@endif
 
    <h1 class="title"> Create Cars </h1>
 
    <form method="POST" action="/uploadsql" enctype="multipart/form-data">
    @csrf
 
        <div class="field">
 
            <label class="lable" for="name">Car Name </label>
 
            <div class="control">
 
                <input type="text" class="input" name="imagename" placeholder="Title" value="" required>
        
            </div>
       
        </div>
    
        <div class="field">
 
            <div class="control">
                 <input type="file" class="form-control-file" name="fileToUpload" aria-describedby="fileHelp">
            </div>
         </div>   
       
        <div class="field">
 
            <div class="control">
 
                <button type="submit" class="button is-link">Create Car</button>
 
            </div>
 
        </div>
 
    </form> 
 
 @endsection

This file create the main look and feel of the example.

There is one text field and two buttons are there.

When the user clicks on “Choose File” button, a pop up window will be opened and user can select image from this window.

Second button is “Create Car” . When it is clicked, system will upload the image into the public->images folder. Also, it will insert the name and path of the image into the database.

On the click event of “Create Car” button, laravel will make the post request to the URL /uploadsql

This URL will execute the storeCar() method from the CarsController.php file.

Below is the source lines for storeCar() method

 public function storeCar(Request $request)
    {
        
        $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 Upload successful');
    }

$destinationPath will get the path to the images folder.

$image will get the original file using the $request variable.

$input[‘imagename’] will hold the value of current time and we will use this variable as the name of the uploaded file.

Below line is uploading the path to the images folder.

$image->move($destinationPath, $input['imagename']);

$dbPath will hold 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.

Go to “http://127.0.0.1:8000/uploadfile” and yes, your upload file example is done.

Download Code For Laravel File Upload

Click here to download source code from github





2. Laravel File Upload Validation Example With MySQL Database

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.