Laravel 9 Image Upload with Preview

1 year 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 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...


How Do you Format a Number as K/M/B in Laravel

In this lesson, we will see how to format a number as K/M/B in Laravel, sometimes we want to display...


How to Override Laravel Fortify Default Registration Redirect

In this lesson, we will see how to override Laravel Fortify default registration redirect, sometimes...


How to Override Laravel Fortify Default Login Redirect

In this lesson, we will see how to override Laravel Fortify default login redirect, sometimes when w...


How to Use the Same Validation Form Request for both Create and Update in Laravel

In this lesson, we will see how to use the same validation form request for both create and update i...


How to Get Raw SQL Output from the Eloquent Model in Laravel 11

In this lesson, we will see how to get raw SQL output from the eloquent model in Laravel 11, sometim...


How to Check if a Record Does Not Exist in Laravel

in this lesson, we will see how to check if a record does not exist in laravel, sometimes you need t...