Laravel 8 Image Upload Tutorial with Validations

Throughout this Laravel 9 Image Upload Tutorial we will share with you how to upload image in laravel 8 with validation example. We will show you upload the image in storage and store into the database table with proper validation like maximum size, file extension should be peg, png, jpg, gif or SVG etc.

Here you need to create two routes and two methods in controller along with a “uploads/” directory of public folder. So guys lets start Laravel 8 Image Upload Tutorial With Validations step by step easy way. The laravel 8 image upload in public or storage directory.

Step 1 : Download Laravel App

You can install a new laravel project or you can skip if you have already installed a laravel app;

composer create-project --prefer-dist laravel/laravel upload-image

Step 2: Setup Database

Create the database in your phpmyadmin and add credentials in your .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_images
DB_USERNAME=root
DB_PASSWORD=

Step 3: Create Model & Migrations

Now create a model and migration file just running the following command which generate two files.

  • One is model
  • Another is migration file
php artisan make:model Image -m

Now navigate the database/migrations directory and open the database\migrations\2020_09_13_082159_create_images_table.php file then add name and path column in your database table.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('path')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
}

Once you have updated your migration, run below command and you seed in your database have created a new table named as images.

php artisan migrate

Fillable Properties: Storing any data we need to add fillable properties in model just like below.

app\Models\Image.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    use HasFactory;

    protected $fillable = [
      'name', 'path'
    ];
}

Step 4: Add Routes

Add two routes in your web.php file one for displaying the form and another is saving image data in database.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageController;


Route::get('images', [ ImageController::class, 'index' ]);
Route::post('images', [ ImageController::class, 'store' ])->name('images.store');

Route::get('/', function () {
    return view('welcome');
});

Step 5: Create Controller

Now create new controller ImageController and add two methods image and store. So one method will handle get method another one for post. So, open the app/Http/Controllers/ImageController.php file and update the below code on it;

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Image;

class ImageController extends Controller
{
    public function index()
    {

      return view('images');
    }

    public function store(Request $request)
    {
        $request->validate([
          'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $image = new Image;

        if ($request->file('file')) {
          $imagePath = $request->file('file');
          $imageName = $imagePath->getClientOriginalName();

          $path = $request->file('file')->storeAs('uploads', $imageName, 'public');
        }

        $image->name = $imageName;
        $image->path = '/storage/'.$path;
        $image->save();

        return back()->with('success', 'Image uploaded successfully');
    }
}

Step 6: Create Blade File

At last step we need to create images.blade.php image and in this file we will create form with file input button. So, open the resources\views\images.blade.php file and update the below code on it;

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Laravel Image Upload Example with Coding Driver</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />

</head>
<body>

<div class="container mt-4">
  <h2>Laravel Image Upload Example with- <a href="https://codingdriver.com/">codingdriver.com</a></h2>
    @if(session()->has('success'))
        <div class="alert alert-success">
            {{ session()->get('success') }}
        </div>
    @endif

    <form method="post" action="{{ route('images.store') }}" enctype="multipart/form-data">
      @csrf
      <div class="form-group">
          <input type="file" name="file" class="form-control{{ $errors->has('file') ? ' is-invalid' : '' }}" >
          @if ($errors->has('file'))
              <span class="invalid-feedback" role="alert">
                  <strong>{{ $errors->first('file') }}</strong>
              </span>
          @endif
      </div>

      <div class="form-group">
        <button type="submit" class="btn btn-success">Save</button>
      </div>
    </form>
</div>
</body>
</html>

Note: Rung the ‘php artisan storage:link’ command which his generate a storage folder linked as the storage>app>public and when you upload the image these both directory updated with the image name.

php artisan storage:link

Step 7: Create “uploads” Directory

Where you want to upload your image, So you need to create new directory “uploads” on public folder with full permission. If you don’t know how to give file permission run below command. Above code send the file in storage directory, you need to give permission your storage directory.

Permission to public folder:

sudo chmod -R 777 public/uploads

Permission to public folder:

sudo chmod -R 777 storage

You can show image easily in you blade file as well.

So guys, Laravel 8 Image Upload example is over now. I hope its work for you if any question please comment below.

1 thought on “Laravel 8 Image Upload Tutorial with Validations”

Leave a Comment