Laravel 11 CRUD Tutorial: Insert, Update, and Delete Products

Laravel 11 CRUD Tutorial: Insert, Update, and Delete Products

AI Reading

Quick summary of this article

This tutorial walks through building a complete product management system in Laravel 11, covering all four CRUD operations: create, read, update, and delete. It includes step-by-step instructions for setting up a new Laravel project, creating a Product model and database migration, building a resource controller, implementing form validation, handling product image uploads, and displaying products using Blade templates. Each product in the system stores a name, description, optional image, and price.

  • Install Laravel 11 using Composer and create a Product model with its migration file using the Artisan command php artisan make:model Product -m.
  • The products database table includes fields for id, name, description, image (nullable), price (decimal with 8 digits and 2 decimal places), and timestamps.
  • Form validation rules require name and description, while price must be numeric; the image upload is optional but restricted to JPEG, PNG, JPG, or GIF files up to 2MB.
  • Product images are stored in the public/uploads directory with a timestamp-based filename to avoid duplicates.
  • Routes are defined using Laravel's resource controller method (Route::resource('products', ProductController::class)), which automatically generates all necessary CRUD routes.

Introduction

CRUD (Create, Read, Update, Delete) operations are fundamental in web applications. Laravel 11 provides powerful tools for handling CRUD operations using Eloquent ORM, Blade templates, and validation.

In this tutorial, we will build a CRUD system in Laravel 11 to manage products. Each product will have a name, description, image, and price. We will cover:

  • Setting up Laravel 11
  • Creating a model and migration
  • Building a controller for CRUD operations
  • Implementing form validation
  • Handling file uploads (product images)
  • Displaying products in a Blade view

By the end of this guide, you will have a fully functional product management system.


Setting Up Laravel 11

Install Laravel 11 using Composer:

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

Navigate to the project directory:

cd laravel11crud

Creating a Model and Migration

Generate a Product model with a migration:

php artisan make:model Product -m

Modify the migration file in database/migrations/ to define the table structure:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description');
        $table->string('image')->nullable();
        $table->decimal('price', 8, 2);
        $table->timestamps();
    });
}

Run the migration:

php artisan migrate

Creating the Product Model

Modify Product.php located in app/Models/Product.php:

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'description', 'image', 'price'];
}

Creating a Controller

Generate a resource controller for products:

php artisan make:controller ProductController --resource

Modify ProductController.php in app/Http/Controllers/:

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::all();
        return view('products.index', compact('products'));
    }

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

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

        if ($request->hasFile('image')) {
            $imageName = time().'.'.$request->image->extension();
            $request->image->move(public_path('uploads'), $imageName);
            $imagePath = 'uploads/' . $imageName;
        } else {
            $imagePath = null;
        }

        Product::create([
            'name' => $request->name,
            'description' => $request->description,
            'image' => $imagePath,
            'price' => $request->price,
        ]);

        return redirect()->route('products.index')->with('success', 'Product created successfully');
    }

    public function edit(Product $product)
    {
        return view('products.edit', compact('product'));
    }

    public function update(Request $request, Product $product)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'required',
            'price' => 'required|numeric',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        if ($request->hasFile('image')) {
            $imageName = time().'.'.$request->image->extension();
            $request->image->move(public_path('uploads'), $imageName);
            $product->image = 'uploads/' . $imageName;
        }

        $product->update($request->except('image'));

        return redirect()->route('products.index')->with('success', 'Product updated successfully');
    }

    public function destroy(Product $product)
    {
        $product->delete();
        return redirect()->route('products.index')->with('success', 'Product deleted successfully');
    }
}

Defining Routes

Update routes/web.php to include routes for CRUD operations:

use App\Http\Controllers\ProductController;

Route::resource('products', ProductController::class);

Creating Blade Templates

Product Create Form with Image Upload

Create resources/views/products/create.blade.php:

@extends('layouts.app')

@section('content')
    <h1>Add Product</h1>
    <form action="{{ route('products.store') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <input type="text" name="name" placeholder="Product Name" required>
        <textarea name="description" placeholder="Product Description" required></textarea>
        <input type="file" name="image">
        <input type="number" step="0.01" name="price" placeholder="Price" required>
        <button type="submit">Add Product</button>
    </form>
@endsection

Summary

In this tutorial, we built a Laravel 11 CRUD system for managing products, including image uploads. We:

  • Created a model and migration for products
  • Built a controller to handle CRUD operations
  • Implemented image uploads and validation
  • Displayed, updated, and deleted products in Blade templates

By following these steps, you now have a fully functional CRUD system for managing products in Laravel 11. You can enhance it further by adding authentication and advanced validation.

Happy coding! 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *