Laravel 9 Image Upload with Preview

2 years ago admin Laravel

In this tutorial, we are going to see how we can upload images in Laravel 9 with preview using javascript.

I assume that you have already a fresh Laravel 9 application installed, a Post Model, and PostController with create and store methods.


Add methods in PostController

So let's add the create and store methods, the first one renders the form, and the second one stores the post with the image.

                                                    
                                                                                                                
<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StorePostRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
         $data = $request->except('_token');
         $file = $request->file('photo');
         $image_name = time() . '_' . 'photo'. '_' . $file->getClientOriginalName();
         $file->move('uploads', $image_name);
         $data['photo'] = 'uploads/'.$image_name;
         Post::create($data);
         return redirect()->route('posts.index')->with([
            'success' => 'Post added successfully'
         ]);
    }
}


Create the routes

Inside routes/web.php we add the routes for the methods we have created.

                                                        
                                                                                                                        
Route::get('post/create', [PostController::class, 'create'])->name('posts.create');
Route::post('post/store', [PostController::class, 'store'])->name('posts.store');

Create blade view

Inside views, we add a new file create.blade.php which holds the form to add the post with the image preview

Photo of a demo

                                                        
                                                                                                                        
@extends('admin.layouts.main')

@section('content')
    <div class="row">
        <div class="col-lg-12 grid-margin stretch-card">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">Create new post</h4>
                    <hr>
                    <form action="{{route('posts.store')}}" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group row">
                                    <label class="col-sm-3 col-form-label">Title (*)</label>
                                    <div class="col-sm-9">
                                        <input type="text" name="title" class="form-control @error('title') is-invalid @enderror"
                                            value="{{old('title')}}" placeholder="Title">
                                        @error('title')
                                            <span class="invalid-feedback" role="alert">
                                                <strong>{{ $message }}</strong>
                                            </span>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group row">
                                    <label class="col-sm-3 col-form-label">Body (*)</label>
                                    <div class="col-sm-9">
                                        <textarea name="body" class="form-control @error('body') is-invalid @enderror"
                                          placeholder="Body">{{old('body')}}</textarea>
                                        @error('body')
                                            <span class="invalid-feedback" role="alert">
                                                <strong>{{ $message }}</strong>
                                            </span>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group row">
                                    <label class="col-sm-3 col-form-label"> Photo (*)</label>
                                    <div class="col-sm-9">
                                        <input type="file" id="photo" name="photo" class="form-control form-control-lg @error('photo') is-invalid @enderror">
                                        @error('photo')
                                            <span class="invalid-feedback" role="alert">
                                                <strong>{{ $message }}</strong>
                                            </span>
                                        @enderror
                                        <div class="mt-2">
                                            <img src="#" id="photo_preview" class="d-none img-fluid rounded mb-2" width="100" height="100">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row my-4">
                            <div class="col-md-12 d-flex justify-content-center">
                                <button type="submit" class="btn btn-primary">
                                    Submit
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection
@section('scripts')
    <script>
        const input = document.getElementById("photo");
        const preview = document.getElementById("photo_preview");
        input.addEventListener('change',function(){
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    preview.classList.remove('d-none');
                    preview.setAttribute('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        });
    </script>
@endsection

Related Tuorials

How to Prevent the Loop Incrementing Operator from Resetting Back to 1 in the Next Pagination Pages in Laravel

In this lesson, we will see how to prevent the loop incrementing operator from resetting back to 1 i...


How to Logout a User from the Other Devices in Laravel 11

In this lesson, we will see how to logout a user from the other devices in Laravel 11, sometimes you...


How to Logout a User from the Current Device in Laravel 11

In this lesson, we will see how to logout a user from the current device in Laravel 11, sometimes yo...


How to Import Multiple Classes from a Single Namespace in Laravel

In this lesson, we will see how to import multiple classes from a single namespace in Laravel by add...


Laravel 11 Livewire CRUD Application Tutorial Part 2

In the second part of this tutorial, we will display all the tasks on the home page and later we wil...


Laravel 11 Livewire CRUD Application Tutorial Part 1

This tutorial will show us how to create a Laravel 11 Livewire CRUD application. The user can c...


How to Conditionally Include a Blade Template in Laravel

In this lesson, we will see how to conditionally include a blade template in Laravel.Sometimes,...


How to Include a Blade Template Only if it Exists in Laravel

In this lesson, we will see how to include a blade template only if it exists in Laravel.Sometimes,&...


How to Pass a Variable to Include in Laravel

In this lesson, we will see how to pass a variable to include in Laravel. Sometimes, we want to pass...


How to the Get the Previous and Next Posts in Laravel

In this lesson, we will see how to get the previous and next posts in Laravel, sometimes when you ge...