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


How to Check if a Record Exists in Laravel

in this lesson, we will see how to check if a record exists in laravel, sometimes you need to check...


How to Decrement Multiple Fields in Laravel

In this lesson, we will see how to decrement multiple fields in Laravel, in the old versions of lara...


How to Increment Multiple Fields in Laravel

In this lesson, we will see how to increment multiple fields in Laravel, in the old versions of lara...


How to Use the Same Request Validation Rules for Storing and Updating in Laravel

In this lesson, we will see how to use the same request validation rules for storing and updating in...


How to Go Back to the Previous URL in Laravel Blade

In this lesson, we will see how to go back to the previous URL in Laravel Blade, sometimes we need t...


How to Add Additional Data to The Resource JSON Response in Laravel

In this lesson, we will see how to add additional data to the resource JSON response in Laravel, let...


How to Specify the Attributes to be Returned in the Laravel Find Method

In this lesson, we will see how to specify the attributes to be returned in the Laravel find method,...


How to Get Data Using Where All in Laravel

In this lesson, we will see how to get data using Where All in Laravel, the Where All method is used...


How to Get Data Using Where Any in Laravel

In this lesson, we will see how to get data using Where Any in Laravel, the Where Any method is used...