upload image in laravel 11 Tutorial

In this Laravel 11 image upload tutorial guide, you’ll discover a step-by-step process for upload image in a Laravel 11 application. Image upload functionality is essential in many projects, and Laravel offers a straightforward method to handle file uploads and store them in a database table.

This includes robust validation, such as checking file size and accepting specific file extensions like jpg, png, gif, or SVG. You can securely upload images to your storage folder, which is accessible via the public folder for seamless integration into your application.

Here’s a tutorial guide on how to integrate image upload functionality in a Laravel 11 application:

#1 Install Laravel App

First, you need to install a new Laravel application using the following command.

composer create-project laravel/laravel laravel-app

Go inside your application:

cd laravel-app

#2 Connect App to Database

Now open your .env file and update the database credentials just like below.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE= #database_name
DB_USERNAME= #database_username
DB_PASSWORD= #database_password

#3 Generate Model and Migration file

Now, its time to generate database model and migration file in Laravel. So just run the below command and its create a model and migration file your application.

php artisan make:model Image -m

Next, open your database/migrations/2019_09_01_114306_create_imagess_table.php file and update your database column on it;

<?php

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

class CreateImagesTable extends Migration {

    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');
    }
}

Once you have updated your migration, run the below command to create your migrations (database table).

php artisan migrate

Add Fillable Property: You need to add the fillable properties in your model. So, open app\Models\Image.php file and update the fillable properties.

protected $fillable = ['name', 'path'];

#4 Create Routes for Upload Image in Laravel

Now open the routes/web.php file and update the following routes on it. One route is show the upload image form and another to store the image in database and storage directory.

<?php

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

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

#5 How to Create Controller

In this step you need to generate a new controller using the following command.

php artisan make:controller ImageController

Now you need to open the app/Http/Controllers/ImageController.php file and upate the following command on it.

<?php

namespace App\Http\Controllers;

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

class ImageController extends Controller
{
    public function index()
    {
      return view('images');
    }

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

        $image = new Image;
        if ($request->file('image')) {
          $imagePath = $request->file('image');
          $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');
    }
}

#6 Make Blade View Files

After the all steps now we will create blade view file to show the image upload form in laravel. You just need to create a “images.blade.php” file in the resources/views directory.

Now you can open the resources\views\images.blade.php file and update the below code on it.

<!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</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</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="image" class="form-control{{ $errors->has('image') ? ' is-invalid' : '' }}" >
          @if ($errors->has('image'))
              <span class="invalid-feedback" role="alert">
                  <strong>{{ $errors->first('image') }}</strong>
              </span>
          @endif
      </div>
      <div class="form-group">
        <button type="submit" class="btn btn-success">Save</button>
      </div>
    </form>
</div>
</body>
</html>

#7 Start App and Test

Now, it’s time to test the upload image in Laravel example. So run the dev server to run your application.

php artisan server

Now hit the below URL in your browser

http://localhost:8000/images