Laravel 9 Image Upload with Preview Example

Laravel 9 Image Upload with Preview Example

In this Laravel 9 Image Upload with Preview example, we will learn how to upload image along with preview before upload in laravel 9. In this laravel 9 image upload example I’ll show you how to validate upload image into folder and then save it into database. In this tutorial before saving image into database we will show preview of the images and then save it into directory. Before uploading the image we will display preview of the image. After successfully image upload into the database and folder we will display success message on the screen.

Laravel 9 Image Upload with Preview

In this step by step Laravel 9 Image Upload with Preview tutorial I’ll demonstrate how to upload image in laravel 9 with preview. I’ll also show you how to upload image in laravel 9 with preview. Please follow the steps given below:

  • Install Laravel 9
  • Setup Database with App
  • Create Model & Migration
  • Create Routes
  • Generate Controller By Artisan Command
  • Create Blade View
  • Implement javascript Code to Show Image Preview
  • Create Images Directory inside Storage/app/public
  • Run Development Server

Install Laravel 9

First of all we need to create a fresh laravel project, download and install Laravel 9 using the below command

composer create-project --prefer-dist laravel/laravel lara9blog

Configure Database In .env file

Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.

.env

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

Create Model & Migration

Now, we have to define table schema for photos table. Open terminal and let’s run the following command to generate a migration along with model file to create photos table in our database.

php artisan make:model Photo -m

Once this command is executed you will find a migration file created under “database/migrations”. lets open migration file and put following code in it –

public function up()
{
    Schema::create('photos', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('path');
        $table->timestamps();
    });
}

Now, run following command to migrate database schema.

php artisan migrate

After, the migration executed successfully the photos table will be created in database.

Create Routes

After this, we need to add following routes in “routes/web.php” file along with a resource route. Lets open “routes/web.php” file and add following route.

routes/web.php

use App\Http\Controllers\ImageUploadController;
 
Route::get('image-upload-preview', [ImageUploadController::class, 'index']);
Route::post('upload-image', [ImageUploadController::class, 'store']);

Create Controller By Artisan Command

Now, lets create a controller for simple image uploading. Create a controller named ImageUploadController using command given below –

php artisan make:controller ImageUploadController

Once the above command executed, it will create a controller file ImageUploadController.php in app/Http/Controllers/ directory. Open the ImageUploadController.php file and put the following code in it.

app/Http/Controllers/ImageUploadController.php

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use App\Models\Photo;
 
class ImageUploadController extends Controller
{
     public function index()
    {
        return view('image-upload');
    }
 
    public function store(Request $request)
    {
         
        $validatedData = $request->validate([
         'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
 
        ]);
 
        $name = $request->file('image')->getClientOriginalName();
 
        $path = $request->file('image')->store('public/images');
 
 
        $save = new Photo;
 
        $save->name = $name;
        $save->path = $path;
 
        return redirect('image-upload-preview')->with('status', 'Image uploaded successfully');
 
    }
}

Note:- Before uploading any file make sure you have created following directory in the storage/app/public folder called images.

Create Blade View

In this step, we will create view/blade file to generate and display Image Upload Form. Lets create a blade file “image-upload.blade.php” in “resources/views/” directory and put the following code in it respectively.

resources/views/image-upload.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 9 Image Upload With Preview</title>
 
  <meta name="csrf-token" content="{{ csrf_token() }}">
 
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
 
 
</head>
<body>
 
<div class="container mt-4">
 
  <h2 class="text-center">Image Upload with Preview in Laravel 9</h2>
 
      <form method="POST" enctype="multipart/form-data" id="upload-image" action="{{ url('upload-image') }}" >
                 
          <div class="row">
 
              <div class="col-md-12">
                  <div class="form-group">
                      <input type="file" name="image" placeholder="Choose image" id="image">
                        @error('image')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                  </div>
              </div>
 
              <div class="col-md-12 mb-2">
                  <img id="preview-image-before-upload" src="https://www.riobeauty.co.uk/images/product_image_not_found.gif"
                      alt="preview image" style="max-height: 250px;">
              </div>
                 
              <div class="col-md-12">
                  <button type="submit" class="btn btn-primary" id="submit">Submit</button>
              </div>
          </div>     
      </form>
</div>
 
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
 
<script type="text/javascript">
      
$(document).ready(function (e) {
 
   
   $('#image').change(function(){
            
    let reader = new FileReader();
 
    reader.onload = (e) => { 
 
      $('#preview-image-before-upload').attr('src', e.target.result); 
    }
 
    reader.readAsDataURL(this.files[0]); 
   
   });
   
});
 
</script>
</div>  
</body>
</html>

Create Images Directory inside Storage/app/public

Before uploading any file make sure you have created following directory in the storage/app/public folder called images.

$path = $request->file('image')->store('public/images');

Start Development Server

Now we are ready to run our example so lets start the development server using following artisan command –

php artisan serve

Now, open the following URL in browser to see the output –

http://localhost:8000/image-upload-preview

Leave a Reply

Your email address will not be published.