Laravel Image Upload Tutorial Example 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

Laravel Image Upload Tutorial Example From Scratch is today’s article.

I will guide you how to upload image in laravel 5.7 app.

We will get the image fro user’s computer using multipart form data.

Then we will add details like car name and path to the uploaded image in the MySQL database.

First of all, watch the below demonstration video.

Step 1. Database and New Project

To create a new project, fire up the below command

laravel new laraimageupload
  • Command will make a new laravel project named “laraimageupload” for you.
  • After this, go to your MySQL database administration tool. Mine is sequel pro but if you are using other than this, then don’t worry. Database related tasks are still same.
  • So go on and make a new MySQL database called “laraImageUpload

Now go to your editor and open your .env file of your laravel project.

In this file, you need to change the below lines

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraImageUpload
DB_USERNAME=root
DB_PASSWORD=
  • My username is root and password is nothing.

Similarly, update other fields as per your machine.

Step 2. A Table in Database

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

For this, run the below command in terminal.

php artisan make:controller CarsController -r -m Car
  • This command will make a new migration file. This file is located at app->database->migrations folder.
  • Inside migrations folder, you will find a new file named “time_create_cars_table.php”

You need to add the below source lines in this “time_create_cars_table.php”

<?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('carname');
            $table->string('carpath');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('cars');
    }
}
  • This file will tell compiler how many field it should add to the database table.
  • up() function includes the names and types of these fields (columns).

Now trigger the below command

php artisan migrate

Finally, this command will make a new table called “Cars” in our database.

Step 3. Making Model and Controller

First of all, trigger the below command

php artisan make:controller CarsController -r -m Car
  • Above command will make a new controller. For this, it will check whether a model called “Car.php” is there or not. Right now it is not, so it will ask you if you want to make model or not.

Write “yes” as the answer. 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, now system have created one controller and one model class.

Navigate to app->Car.php file. Source code for this file is as the below

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Write down the below coding lines 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('uploadimage');
    }

    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->carname = request('imagename');
        $car->carpath = $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)
    {
        //
    }
}

Controller includes several useful functions which I will teach you later.

Step 4. About Routes

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

This file have the following code snippet.

<?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('uploadimage','CarsController@index');
Route::post('uploadsql','CarsController@storeCar');

Mainly, there are two routes are there.

Route::get('uploadimage','CarsController@index');
Route::post('uploadsql','CarsController@storeCar');
  • First one is the reference to the index() function from CarsController.php file.
  • Second line is executing storeCar() function. URL for this is uploadsql.

Images Folder

Make a new folder named “images” inside a folder called “public

All the images will be uploaded in this “images” folder.

Step 5. A new Blade Files

Go to resources->views folder and make a new file named “layout.blade.php”

Write down the below source snippet in this 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>
  • This file includes some link to css stylesheet.
  • Now in the same directory, make a new file and give it a name “uploadimage.blade.php

Add the following code lines in “uploadimage.blade.php

@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 will create the view of the main screen.
  • Main screen includes one text field and two buttons.
  • User will enter the name of the car in this text field. Two buttons are : Choose File and Create Cars 
  • when the user clicks Choose File button, system will pop up one new window. This window allows user to select image.
  • After selecting image, user will click “Create Cars” button, and system will upload the image into the images folder.
  • Along with uploadation, system will also add car name and car path into the MySQL database.
  • Create Cars” button will access /uploadsql URL and it will execute the storeCar() method from CarsController.php

Source code for storeCar() method is as the below

 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->carname = request('imagename');
        $car->carpath = $dbPath;
 
        $car->save();
        //return view('uploadfile');
        return back()->with('success','Image Upload successful');
    }
  • First line will get the path to the images folder where we want to upload images.
  • Second one is fetching the file from the $request folder.
  • Third one will store the time stamp in $input[‘imagename’]. We will use it as the name of the image.
  • Fourth line will move the image into the images folder. (upload the image)
  • Fifth line is the variable with value as the path which we will enter in the database.
  • Sixth, Seventh and Eighth lines are inserting the values in the database.
  • Now run your project using “php artisan serve” command.

Go to “http://127.0.0.1:8000/uploadimage” and you are able to upload images.

Download Code For Laravel Image Upload

Github link to download code