Laravel 9 Image Upload Image Tutorial Example

Laravel 9 Image Upload Image Example; In this tutorial you will learn how to upload image in laravel app. Uploading file in any admin project is very requirement and now a days upload image is very basic needed.

Laravel provides a very simple way to file uploading system and store it in database table with proper validation like maximum size, file extension should be peg, png, jpg, gif or SVG etc. Let’s see the step by step guide to upload image in public or storage folder with laravel application easy way.

Step 1: Create Model & Migrations

First create model and migration file, run the below command which is generate both model and migration.

php artisan make:model Image -m

Add the blow code in your migration file.

database/migrations/2019_09_01_114306_create_images_table.php

<?php

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

class CreateImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('path')->nullable();
            $table->timestamps();
        });
    }

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

After updating the migration file run the below command which is generate a table in your database.

php artisan migrate

Step 2: Create Routes

Add two routes in your web.php file one for displaying the form and another is saving image data in database.

Route::get('images', 'ImageController@index');
Route::post('images', 'ImageController@store')->name('images.store');

Step 3: Create Controller

Now create new controller ImageController and add two methods image and store. So one method will handle get method another one for post. You can use below code in your controller.

app/Http/Controllers/ImageController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Image;

class ImageController extends Controller
{
    public function index()
    {

      return view('images');
    }

    public function store(Request $request)
    {
        $request->validate([
          'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $image = new Image;

        if ($request->file('file')) {
          $imagePath = $request->file('file');
          $imageName = $imagePath->getClientOriginalName();

          $path = $request->file('file')->storeAs('uploads', $imageName, 'public');
        }

        $image->name = $imageName;
        $image->path = '/storage/'.$path;
        $image->save();

        return back()->with('success', 'Image uploaded successfully');
    }
}

Step 4: Create Blade File

In the last step you need to create images.blade.php file in you view directory and put the below code on it.

resources\views\images.blade.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Laravel Image Upload Example with Coding Driver</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />

</head>
<body>

<div class="container mt-4">
  <h2>Laravel Image Upload Example with- <a href="https://codingdriver.com/">codingdriver.com</a></h2>
    @if(session()->has('success'))
        <div class="alert alert-success">
            {{ session()->get('success') }}
        </div>
    @endif

    <form method="post" action="{{ route('images.store') }}" enctype="multipart/form-data">
      @csrf
      <div class="form-group">
          <input type="file" name="file" class="form-control{{ $errors->has('file') ? ' is-invalid' : '' }}" >
          @if ($errors->has('file'))
              <span class="invalid-feedback" role="alert">
                  <strong>{{ $errors->first('file') }}</strong>
              </span>
          @endif
      </div>

      <div class="form-group">
        <button type="submit" class="btn btn-success">Save</button>
      </div>
    </form>
</div>
</body>
</html>

Step 5: Create “uploads” Directory

Where you want to upload your image, So you need to create new directory “uploads” on public folder with full permission. If you don’t know how to give file permission run below command.

Permission to public folder:

sudo chmod -R 777 public/uploads

Permission to public folder:

sudo chmod -R 777 storage

Read Also: File Upload in Laravel 7 – How To upload Image in laravel 7 Example

1 thought on “Laravel 9 Image Upload Image Tutorial Example”

Leave a Comment