Laravel 11 CRUD (Create, Read, Update, Delete)

Step 1: Install Laravel

If you haven’t already, create a new Laravel 11 project:

composer create-project laravel/laravel customer-crud

Step 2: Create the Customer Model and Migration

Generate a model with a migration:

php artisan make:model Customer -m

This command creates:

  1. A model file at app/Models/Customer.php
  2. A migration file in the database/migrations folder

Step 3: Define Fields in the Migration

Open the generated migration file in database/migrations and define the fields:

public function up()
{
    Schema::create('customers', function (Blueprint $table) {
        $table->id();
        $table->string('fname');
        $table->string('lname');
        $table->string('name')->nullable();
        $table->string('email')->unique();
        $table->timestamps();
    });
}

Run the migration to create the customers table:

php artisan migrate

Step 4: Set Up the Model

In the Customer model file app/Models/Customer.php, define the fillable fields:

namespace App\Models;

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

class Customer extends Model
{
    use HasFactory;

    protected $fillable = [
        'fname',
        'lname',
        'name',
        'email',
    ];
}

Step 5: Create a Controller

Generate a controller to handle the CRUD operations:

php artisan make:controller CustomerController --resource

This command creates a CustomerController with resource methods. Open app/Http/Controllers/CustomerController.php and implement CRUD functionality:

namespace App\Http\Controllers;

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

class CustomerController extends Controller
{
    public function index()
    {
        $customers = Customer::all();
        return view('customers.index', compact('customers'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'fname' => 'required|string|max:255',
            'lname' => 'required|string|max:255',
            'email' => 'required|email|unique:customers,email',
        ]);

        Customer::create($request->all());

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

    public function show(Customer $customer)
    {
        return view('customers.show', compact('customer'));
    }

    public function edit(Customer $customer)
    {
        return view('customers.edit', compact('customer'));
    }

    public function update(Request $request, Customer $customer)
    {
        $request->validate([
            'fname' => 'required|string|max:255',
            'lname' => 'required|string|max:255',
            'email' => 'required|email|unique:customers,email,' . $customer->id,
        ]);

        $customer->update($request->all());

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

    public function destroy(Customer $customer)
    {
        $customer->delete();

        return redirect()->route('customers.index')->with('success', 'Customer deleted successfully.');
    }
}

Step 6: Set Up Routes

Open routes/web.php and define resource routes for the customer:

use App\Http\Controllers\CustomerController;

Route::resource('customers', CustomerController::class);

Step 7: Create Blade Views

1. resources/views/customers/index.blade.php

@extends('layouts.app')

@section('content')
    <h1>Customers</h1>
    <a href="{{ route('customers.create') }}">Add New Customer</a>

    <table>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
            <th>Actions</th>
        </tr>
        @foreach ($customers as $customer)
            <tr>
                <td>{{ $customer->fname }}</td>
                <td>{{ $customer->lname }}</td>
                <td>{{ $customer->email }}</td>
                <td>
                    <a href="{{ route('customers.show', $customer) }}">Show</a>
                    <a href="{{ route('customers.edit', $customer) }}">Edit</a>
                    <form action="{{ route('customers.destroy', $customer) }}" method="POST" style="display:inline;">
                        @csrf
                        @method('DELETE')
                        <button type="submit">Delete</button>
                    </form>
                </td>
            </tr>
        @endforeach
    </table>
@endsection

2. resources/views/customers/create.blade.php

@extends('layouts.app')

@section('content')
    <h1>Add Customer</h1>

    <form action="{{ route('customers.store') }}" method="POST">
        @csrf
        <label>First Name:</label>
        <input type="text" name="fname" required>
        <label>Last Name:</label>
        <input type="text" name="lname" required>
        <label>Email:</label>
        <input type="email" name="email" required>
        <button type="submit">Save</button>
    </form>
@endsection

3. resources/views/customers/edit.blade.php

@extends('layouts.app')

@section('content')
    <h1>Edit Customer</h1>

    <form action="{{ route('customers.update', $customer) }}" method="POST">
        @csrf
        @method('PUT')
        <label>First Name:</label>
        <input type="text" name="fname" value="{{ $customer->fname }}" required>
        <label>Last Name:</label>
        <input type="text" name="lname" value="{{ $customer->lname }}" required>
        <label>Email:</label>
        <input type="email" name="email" value="{{ $customer->email }}" required>
        <button type="submit">Update</button>
    </form>
@endsection

Step 8: Set Up Layouts

Add a layouts/app.blade.php file to structure the page, with a @yield('content') placeholder for content.

<!DOCTYPE html>
<html>
<head>
    <title>Customer CRUD</title>
</head>
<body>
    <div class="container">
        @yield('content')
    </div>
</body>
</html>

Step 9: Run the Application

Run the development server:

php artisan serve

Visit http://127.0.0.1:8000/customers to manage customers with CRUD operations. This simple Laravel 11 CRUD app provides all the essential features for managing customer data!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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