Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 CRUD with Image Upload Tutorial

Last Updated on April 12, 2024 by

In Laravel 11, CRUD with image upload allows users to create, read, update, and delete records with images that associate with these records in the database.

Let’s get started to build a complete CRUD application with image upload feature:

Step 1: Install Laravel 11 Project

Run the following composer command to install laravel 11 application:

composer create-project --prefer-dist laravel/laravel MyCRUD

Step 2: Database Configuration

Edit .env file from root folder of project, and configure database details in it:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

Step 3: Create Model and Migration

Create model and migration to perform crud with image upload functionality in project. Use the following command to create these two files:

php artisan make:model Car -m

Edit the migration file (database/migrations/_create_cars_table.php) to define the schema for your cars table: like the following:


    Schema::create('cars', function (Blueprint $table) {
        $table->id();
        $table->string('make');
        $table->string('model');
        $table->integer('year');
        $table->string('image')->nullable();
        $table->timestamps();
    });

Run the migration command to create the cars table:

php artisan migrate

Step 4: Create Controller

Run the artisan make controller command to create a car controller file:

php artisan make:controller CarController

Step 5: Implement CRUD Operations Methods in Controller

Edit CarController.php file from app/http/controllers folder, and implement the CRUD with image upload operations methods into it to handle operations with database:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Car;
use Illuminate\Support\Facades\Storage;

class CarController extends Controller
{
    public function index()
    {
        $cars = Car::all();
        return view('cars.index', compact('cars'));
    }

    public function create()
    {
        return view('cars.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'make' => 'required',
            'model' => 'required',
            'year' => 'required|integer|min:1900|max:' . (date('Y') + 1),
            'image' => 'image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        $car = new Car([
            'make' => $request->get('make'),
            'model' => $request->get('model'),
            'year' => $request->get('year'),
        ]);

        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            Storage::disk('public')->put($imageName, file_get_contents($image));
            $car->image = $imageName;
        }

        $car->save();

        return redirect('/cars')->with('success', 'Car saved successfully!');
    }

    public function edit($id)
    {
        $car = Car::findOrFail($id);
        return view('cars.edit', compact('car'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'make' => 'required',
            'model' => 'required',
            'year' => 'required|integer|min:1900|max:' . (date('Y') + 1),
            'image' => 'image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        $car = Car::findOrFail($id);
        $car->make = $request->get('make');
        $car->model = $request->get('model');
        $car->year = $request->get('year');

        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            Storage::disk('public')->put($imageName, file_get_contents($image));
            $car->image = $imageName;
        }

        $car->save();

        return redirect('/cars')->with('success', 'Car updated successfully!');
    }

    public function destroy($id)
    {
        $car = Car::findOrFail($id);
        if ($car->image) {
            Storage::disk('public')->delete($car->image);
        }
        $car->delete();
        return redirect('/cars')->with('success', 'Car deleted successfully!');
    }
}

Step 6: Define Routes

Define routes in routes/web.php for handle CRUD with image upload operations requests in project:

Route::resource('cars', 'CarController');

Step 7: Create the Views

Create views for your CRUD with image upload operations in the resources/views folder.

index.blade.php: Display a list of cars.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 11 CRUD with Image Upload Tutorial - itcodStuff.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h2>Cars</h2>
                <a href="{{ route('cars.create') }}" class="btn btn-primary mb-3">Add Car</a>
                <table class="table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Make</th>
                            <th>Model</th>
                            <th>Year</th>
                            <th>Image</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($cars as $car)
                        <tr>
                            <td>{{ $car->id }}</td>
                            <td>{{ $car->make }}</td>
                            <td>{{ $car->model }}</td>
                            <td>{{ $car->year }}</td>
                            <td>
                                @if($car->image)
                                <img src="{{ asset('storage/' . $car->image) }}" alt="{{ $car->make }}" class="img-thumbnail" style="width: 100px;">
                                @else
                                No Image
                                @endif
                            </td>
                            <td>
                                <a href="{{ route('cars.edit', $car->id) }}" class="btn btn-sm btn-primary">Edit</a>
                                <form action="{{ route('cars.destroy', $car->id) }}" method="POST" style="display: inline;">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')">Delete</button>
                                </form>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>

create.blade.php: Form for creating a new car.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Car - Laravel 11 CRUD with Image Upload Tutorial - itcodStuff.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <h2>Add Car</h2>
                <form action="{{ route('cars.store') }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    <div class="mb-3">
                        <label for="make" class="form-label">Make</label>
                        <input type="text" class="form-control" id="make" name="make" required>
                    </div>
                    <div class="mb-3">
                        <label for="model" class="form-label">Model</label>
                        <input type="text" class="form-control" id="model" name="model" required>
                    </div>
                    <div class="mb-3">
                        <label for="year" class="form-label">Year</label>
                        <input type="number" class="form-control" id="year" name="year" min="1900" max="{{ date('Y') + 1 }}" required>
                    </div>
                    <div class="mb-3">
                        <label for="image" class="form-label">Image</label>
                        <input type="file" class="form-control" id="image" name="image">
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

edit.blade.php: Form for editing an existing car.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Car - Laravel 11 CRUD with Image Upload Tutorial - itcodStuff.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <h2>Edit Car</h2>
                <form action="{{ route('cars.update', $car->id) }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    @method('PUT')
                    <div class="mb-3">
                        <label for="make" class="form-label">Make</label>
                        <input type="text" class="form-control" id="make" name="make" value="{{ $car->make }}" required>
                    </div>
                    <div class="mb-3">
                        <label for="model" class="form-label">Model</label>
                        <input type="text" class="form-control" id="model" name="model" value="{{ $car->model }}" required>
                    </div>
                    <div class="mb-3">
                        <label for="year" class="form-label">Year</label>
                        <input type="number" class="form-control" id="year" name="year" value="{{ $car->year }}" min="1900" max="{{ date('Y') + 1 }}" required>
                    </div>
                    <div class="mb-3">
                        <label for="image" class="form-label">Image</label>
                        <input type="file" class="form-control" id="image" name="image">
                    </div>
                    <div class="mb-3">
                        @if($car->image)
                        <img src="{{ asset('storage/' . $car->image) }}" alt="{{ $car->make }}" class="img-thumbnail" style="width: 100px;">
                        @else
                        No Image
                        @endif
                    </div>
                    <button type="submit" class="btn btn-primary">Update</button>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

Step 8: Test Your Application

Run the following command to start application for testing:

php artisan serve

Now use http://127.0.0.1:8000/cars url on browser to perform CRUD with image upload operations.

In this Laravel 11 with CRUD with Image Upload tutorial, created a controller that has methods to create, read, update and delete records from the database, then create routes that will handle CRUD operation requests and finally create forms and list views using Bootstrap 5 Which allows users to manage car records efficiently.

Leave a Comment