upload image in laravel 8

How to upload image in Laravel 8?

Today, I will give you an example of “How to upload image in Laravel 8”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

Steps to upload image and display in Blade file in Laravel

We will create a migration, model, and controller and we will write some logic for uploading image in our system folder and save image names with a unique name in our table in the database and display these uploaded images in our blade file in the Laravel application.

First, what we’re doing here, This is the example :

upload image laravel 8

display image in blade file in laravel

Let’s get started.

Generating Migration

php artisan make:migration create_categories_table

Migration Structures

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('cat_name',25);
            $table->string('cat_banner',50);
            $table->softDeletes();
            $table->index(['deleted_at']);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

Run Migration

php artisan migrate

Create Model

php artisan make:model Category

app\Models\Category.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;


class Category extends Model
{
   
    use SoftDeletes;
    use HasFactory;

}

Create a Controller

php artisan make:controller ProductController

Define Web Routes

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;


Route::prefix('admin')->group(function(){

Route::get('/add-category', [ProductController::class, 'addcategory'])->name('add.category');
Route::get('/list-category', [ProductController::class, 'listcategory'])->name('list.category');
Route::post('/store-category', [ProductController::class, 'storecategory'])->name('store.category');

});

app\Http\Controllers\ProductController.php

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Category;

use Illuminate\Http\Request;
use Session;

class ProductController extends Controller
{
    public function addcategory(){
        return view('category.create');
    }

    public function listcategory(){
        $category = Category::orderBy('cat_name')->get();
        return view('category.list',compact('category'));
    }

    public function storecategory(Request $request){
        $request->validate([
            'cat_name' => 'required',
            'banner_img' => 'required|max:1048',
        ]);
         #Handle File Upload
         if($request->hasfile('banner_img'))
            {
                $name = uniqid() . '_' . time(). '.' . $request->banner_img->getClientOriginalExtension();
                $path = public_path() .'/uploads/cat_banner_img';
                $request->banner_img->move($path, $name);
                $banner_img = $name;
            }else{
            $banner_img = null;
            }
        $cat = new Category();
        $cat->cat_name = $request->cat_name;
        $cat->cat_banner = $banner_img;
        $cat->save();
        return redirect()->route('list.category')->with('flash_message_success','Category added Successfully !');
    }
}

Create Blade Files

We create a category folder in views and then create these 2 files given below-:

  • create.blade.php
  • list.blade.php

resources\views\category\create.blade.php

upload image laravel
  <div class="col-md-12">
          <div class="card">
            <div class="card-header card-header-primary">
              <h4 class="card-title">Add Category</h4>
              <p class="card-category">Complete your Categories</p>
            </div>
            <div class="card-body">
              <form action="{{route('store.category')}}" method="POST" id="category" name="add_category" autocomplete="off" enctype="multipart/form-data">
                @csrf
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <label class="bmd-label-floating">Category Name</label>
                      <input type="text" class="form-control" name="cat_name">
                      @if ($errors->has('cat_name'))
                      <span class="errormsg text-danger">{{ $errors->first('cat_name') }} </span>
                      @endif
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group bmd-form-group is-focused file-input">
                      <label class="bmd-label-floating">Category Banner</label>
                      <input type="file" name="banner_img" class="form-control" accept="image">
                    </div>
                    @if ($errors->has('banner_img'))
                    <span class="errormsg text-danger">{{ $errors->first('banner_img') }} </span>
                    @endif
                  </div>
                </div>
                <button type="submit" class="btn btn-primary pull-left">Save</button>
                <div class="clearfix"></div>
              </form>
            </div>
          </div>
        </div>

resources\views\category\list.blade.php

show images in blade file in laravel
  <div class="col-md-12">
            <div class="row justify-content-end mb-1">
               <div class="col-sm-12 float-right">
                  @if(Session::has('flash_message_success'))
                  <div class="alert alert-success alert-dismissible p-2">
                     <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                     <strong>Success!</strong> {!! session('flash_message_success')!!}.
                  </div>
                  @endif
               </div>
            </div>
            <div class="card">
               <div class="card-header card-header-primary">
                  <h4 class="card-title ">Category List</h4>
               </div>
               <div class="card-body">
                  <div class="table-responsive">
                     <table class="table">
                        <thead class=" text-primary">
                           <th>
                              Category Name
                           </th>
                           <th>
                              Category Banner
                           </th>
                           <th>
                              Created At
                           </th>
                           <th>Action</th>
                        </thead>
                        <tbody>
                           @foreach($category as $cat)
                           <tr>
                              <td>
                                 {{ $cat->cat_name }}
                              </td>
                              @if(empty($cat->cat_banner))
                              <td>
                                 <h6>No Image Found !</h6>
                              </td>
                              @else
                              <td>
                                 <a href="{{ url('/uploads/cat_banner_img/'.$cat->cat_banner) }}" target="_blank" title="view category Banner">
                                 <img src="{{ url('/uploads/cat_banner_img/'.$cat->cat_banner) }}" width="110" height="40" /> </a>
                              </td>
                              @endif
                              <td class="text-primary">
                                 {{  date('j \\ F Y', strtotime($cat->created_at)) }}
                              </td>
                              <td>
                                 Action
                            </td>
                           </tr>
                           @endforeach
                        </tbody>
                     </table>
                  </div>
               </div>
            </div>
         </div>

Recommended Article:- Display Session Flash Message in Laravel.

Run Application :

127.0.0.1:8000/add-category

Output :

display image in laravel from database

image list in blade file in laravel

Category Table :

store images in database in laravel
127.0.0.1:8000/list-category
image list in laravel foreach loop

System Local Storage :

image store in storage in laravel

We learned, how to upload image in laravel 8 and display images in blade file in the Laravel application with the help of following a few steps, if you have any queries, please ask below the comment section.

Related article: Upload multiple images in Laravel.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com