Laravel Image Upload With Preview

Updated 2 weeks ago admin PHP / Laravel

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

I assume that you already have a fresh Laravel application installed, a Post Model, and a 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.

@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