Laravel 8 Image Upload with Preview Tutorial
https://laratutorials.com/laravel-8-image-upload-with-preview-tutorial/
Laravel 8 Image Upload with Preview Tutorial
Laravel 8 image upload with preview tutorial. In this post, i will share with you on how to upload image with preview using jQuery in laravel 8.
As well as display preview of image and validate image file data on server side before upload to database.
In this post example, i will create image upload form with preview in laravel. And display preview of image before upload to database with validation in laravel 8.
Laravel Preview Image Before Upload
Simple steps to preview image before upload in laravel 8 app:
Step 1 – Install Laravel 8 Application
Step 2 – Configuring Database Details
Step 3 – Create Image Model & Migration
Step 4 – Create Routes
Step 5 – Creating Controller
Step 6 – Create Image Upload Preview Form
Step 7 – Link storage/app/public/image Directory
Step 8 – Start Development Server
Step 9 – Run Laravel 8 Image Upload with Preview App On Browser
Step 1 – Install Laravel 8 Application
In step 1, open your terminal and navigate to your local web server directory using the following command:
Then install laravel 8 latest application using the following command:
Step 2 – Configuring Database Details
In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following:DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=db nameDB_USERNAME=db user nameDB_PASSWORD=db password
Step 3 – Create Image Model & Migration
In step 3, open command prompt and navigate to your project by using the following command:
Then create model and migration file by using the following command:
The above command will create two files into your laravel 8 image upload tutorial app, which is located inside the following locations:
LaravelImageUploadPreview/app/Models/Image.php
LaravelImageUploadPreview/database/migrations/create_images_table.php
So, find create_images_table.php file inside LaravelImageUploadPreview/database/migrations/ directory. Then open this file and add the following code into function up() on this file: public function up() { Schema::create('images', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('path'); $table->timestamps(); }); }
Now, open again your terminal and type the following command on cmd to create tables into your selected database:
Step 4 – Create Routes
In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:<?phpuse Illuminate\Support\Facades\Route;use App\Http\Controllers\ImageUploadController;/*|--------------------------------------------------------------------------| 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('image-upload-preview', [ImageUploadController::class, 'index']);Route::post('upload', [ImageUploadController::class, 'upload']);
Step 5 – Creating Controller
In step 5, create image upload controller by using the following command:
The above command will create ImagUploadController.php file, which is located inside LaravelImageUpload/app/Http/Controllers/ directory.
The following laravel validation rules will validate image file before upload/save into database: $validatedData = $request->validate([ 'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048', ]);
So open ImagUploadController.php file and add the following code into it:<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Models\Image;class ImageUploadController extends Controller{ public function index() { return view('image-upload-preview'); } public function upload(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('uploads'); $save = new Image; $save->name = $name; $save->path = $path; $save->save(); return redirect('image')->with('status', 'Image Has been uploaded successfully with validation in laravel'); }}
The following single line of code will upload image inside storage/app/upload directory: $path = $request->file('image')->store('uploads');
Step 6 – Create Image Upload Form
In step 6, create new blade view file that named image-upload-preview.php inside resources/views directory for image upload with preview form.
Note that, the following jQuery code display image preview before upload: <script type="text/javascript"> $('#image').change(function(){ let reader = new FileReader(); reader.onload = (e) => { $('#preview-image').attr('src', e.target.result); } reader.readAsDataURL(this.files[0]); }); </script>
And following code display error message in laravel image upload with preview forms. So do not forget to add the following code along laravel forms fields: @error('image') <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div> @enderror
Don’t worry i have already added the jquery image preview code and display validation error message code along with each form fields.
So, you can add the following php and html form code into image-upload-preview.blade.php:<!DOCTYPE html><html><head> <title>Laravel 8 Image Upload with Preview Tutorial</title> <meta name="csrf-token" content="{{ csrf_token() }}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script></head><body><div class="container mt-4"> @if(session('status')) <div class="alert alert-success"> {{ session('status') }} </div> @endif <div class="card"> <div class="card-header text-center font-weight-bold"> <h2>Laravel 8 Preview Image Before Upload</h2> </div> <div class="card-body"> <form method="POST" enctype="multipart/form-data" id="image-upload-preview" action="{{ url('upload') }}" > <div class="row"> <div class="col-md-12"> <div class="form-group"> <input type="file" name="image" placeholder="Choose image" id="image"> @error('name') <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" 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">Submit</button> </div> </div> </form> </div> </div> <script type="text/javascript"> $('#image').change(function(){ let reader = new FileReader(); reader.onload = (e) => { $('#preview-image').attr('src', e.target.result); } reader.readAsDataURL(this.files[0]); }); </script></div></body></html>
Step 7 – Link storage/app/public/image Directory
Now, open the command prompt and type the following command to get images from storage folder:
Note that, in this example, the image will be upload on the following path – storage/app/public/images.
Step 8 – Start Development Server
Finally, open your command prompt again and run the following command to start development server for your laravel 8 image upload application:
Step 9 – Run Laravel 8 Image Upload with Preivew App On Browser
In step 8, open your browser and fire the following url into your browser:
Last updated