How to Create CRUD Operation in Laravel 11

Hey developers! If you're diving into the world of web development with Laravel 11, you're in for a treat. Today, I'm excited to guide you through the fundamentals of implementing CRUD operations in Laravel 11. Laravel has long been celebrated for its elegance and simplicity in building web applications, and version 11 brings even more power to the table.

In this article, we'll embark on a journey to understand how to implement CRUD operations in Laravel 11. Also, we will use Bootstrap 5 to create a view.

So, let's see the Laravel 11 CRUD operation example and the CRUD application in laravel 11.

laravel_11

Step-by-Step Guide to Creating CRUD Operations in Laravel 11

Step 1: Installing Laravel 11

Before we can dive into building our CRUD operations, we need to set up our Laravel environment. In this step, I'll guide you through the process of installing Laravel 11 on your local machine.

composer create-project laravel/laravel example-app

 

Step 2: MySQL Database Configuration

Once you've set up Laravel and established a solid foundation, it's time to configure your MySQL database.

To get started, navigate to your Laravel project directory and open the .env file. 

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 Migration

Now, we'll create migration using the following command.

php artisan make:migration create_items_table --create=items

Migration:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('items', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('items');
    }
};

After that, migrate the table into the database using the following command.

php artisan migrate

 

Step 4: Create Form Request Validation Class

In Laravel 11, validating incoming requests is a crucial step to ensure data integrity and security. To streamline this process, we create Form Request Validation Classes.

php artisan make:request ItemStoreRequest

app/Http/Requests/ItemStoreRequest.php

<?php
  
namespace App\Http\Requests;
  
use Illuminate\Foundation\Http\FormRequest;
  
class ItemStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }
  
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array|string>
     */
    public function rules(): array
    {
        return [
            'name' => 'required',
            'detail' => 'required'
        ];
    }
}

Now, we'll create a form request for the update using the following command.

php artisan make:request ItemUpdateRequest

app/Http/Requests/ItemUpdateRequest.php

<?php
   
namespace App\Http\Requests;
  
use Illuminate\Foundation\Http\FormRequest;
  
class ItemUpdateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array|string>
     */
    public function rules(): array
    {
        return [
            'name' => 'required',
            'detail' => 'required'
        ];
    }
}
 
Step 5: Create Controller and Model

Now that we have our database structure and validation rules set up, it's time to create the Controller and Model in Laravel 11.

php artisan make:controller ItemController --resource --model=Item

app/Http/Controllers/ItemController.php

<?php
    
namespace App\Http\Controllers;
    
use App\Models\Item;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;
use App\Http\Requests\ItemStoreRequest;
use App\Http\Requests\ItemUpdateRequest;
    
class ItemController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        $items = Item::latest()->paginate(5);
          
        return view('items.index', compact('items'))
                    ->simplePaginate(10);
    }
    
    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        return view('items.create');
    }
    
    /**
     * Store a newly created resource in storage.
     */
    public function store(ItemStoreRequest $request): RedirectResponse
    {   
        Item::create($request->validated());
           
        return redirect()->route('items.index')
                         ->with('success', 'Item created successfully.');
    }
  
    /**
     * Display the specified resource.
     */
    public function show(Item $item): View
    {
        return view('items.show', compact('item'));
    }
  
    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Item $item): View
    {
        return view('items.edit', compact('item'));
    }
  
    /**
     * Update the specified resource in storage.
     */
    public function update(ItemUpdateRequest $request, Item $item): RedirectResponse
    {
        $item->update($request->validated());
          
        return redirect()->route('items.index')
                        ->with('success','Item updated successfully');
    }
  
    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Item $item): RedirectResponse
    {
        $item->delete();
           
        return redirect()->route('items.index')
                        ->with('success','Item deleted successfully');
    }
}

Open the Item.php file located in the app/Models directory.

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Item extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name',
        'detail',
    ];
}

 

Step 6: Create a Resource Route

We need to add a resource route to integrate the CRUD operations in laravel 11.

Open routes/web.php: Navigate to the routes directory in your Laravel project and open the web.php file.

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ItemController;
  
Route::get('/', function () {
    return view('welcome');
});
  
Route::resource('items', ItemController::class);

 

Step 7: Update AppServiceProvider

To enhance the pagination functionality with Bootstrap 5, we'll need to import it into our Laravel application. We'll achieve this by updating the AppServiceProvider.php file.

This step ensures that our pagination views are styled using Bootstrap 5, providing a modern and responsive user interface.

app/Provides/AppServiceProvider.php

<?php
  
namespace App\Providers;
  
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;
  
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
           
    }
  
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Paginator::useBootstrapFive();
    }
}
 
Step 8: Create Blade Files

In this step, we'll create the necessary Blade files to display our items, create new items, edit existing items, and show individual items in our laravel 11 application.

resources/views/items/layout.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Create CRUD Operation in Laravel 11 - Techsolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
<body>
      
<div class="container">
    @yield('content')
</div>
      
</body>
</html>

resources/views/items/index.blade.php

@extends('items.layout')

@section('content')

<div class="card mt-5">
  <h2 class="card-header">Laravel 11 CRUD Operation - Techsolutionstuff</h2>
  <div class="card-body">
          
        @if(session('success'))
            <div class="alert alert-success" role="alert">{{ session('success') }}</div>
        @endif
  
        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
            <a class="btn btn-success btn-sm" href="{{ route('items.create') }}"> <i class="fa fa-plus"></i> Create New Item</a>
        </div>
  
        <table class="table table-bordered table-striped mt-4">
            <thead>
                <tr>
                    <th width="80px">No</th>
                    <th>Name</th>
                    <th>Details</th>
                    <th width="250px">Action</th>
                </tr>
            </thead>
  
            <tbody>
            @forelse ($items as $item)
                <tr>
                    <td>{{ ++$i }}</td>
                    <td>{{ $item->name }}</td>
                    <td>{{ $item->detail }}</td>
                    <td>
                        <form action="{{ route('items.destroy', $item->id) }}" method="POST">
             
                            <a class="btn btn-info btn-sm" href="{{ route('items.show', $item->id) }}"><i class="fa-solid fa-list"></i> Show</a>
              
                            <a class="btn btn-primary btn-sm" href="{{ route('items.edit', $item->id) }}"><i class="fa-solid fa-pen-to-square"></i> Edit</a>
             
                            @csrf
                            @method('DELETE')
                
                            <button type="submit" class="btn btn-danger btn-sm"><i class="fa-solid fa-trash"></i> Delete</button>
                        </form>
                    </td>
                </tr>
            @empty
                <tr>
                    <td colspan="4">There are no items.</td>
                </tr>
            @endforelse
            </tbody>
  
        </table>
        
        {!! $items->links() !!}
  
  </div>
</div>  
@endsection

resources/views/items/create.blade.php

@extends('items.layout')

@section('content')

<div class="card mt-5">
  <h2 class="card-header">Add New Item</h2>
  <div class="card-body">
  
    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
        <a class="btn btn-primary btn-sm" href="{{ route('items.index') }}"><i class="fa fa-arrow-left"></i> Back</a>
    </div>
  
    <form action="{{ route('items.store') }}" method="POST">
        @csrf
  
        <div class="mb-3">
            <label for="name" class="form-label"><strong>Name:</strong></label>
            <input 
                type="text" 
                name="name" 
                class="form-control @error('name') is-invalid @enderror" 
                id="name" 
                placeholder="Name">
            @error('name')
                <div class="form-text text-danger">{{ $message }}</div>
            @enderror
        </div>
  
        <div class="mb-3">
            <label for="detail" class="form-label"><strong>Detail:</strong></label>
            <textarea 
                class="form-control @error('detail') is-invalid @enderror" 
                style="height:150px" 
                name="detail" 
                id="detail" 
                placeholder="Detail"></textarea>
            @error('detail')
                <div class="form-text text-danger">{{ $message }}</div>
            @enderror
        </div>
        <button type="submit" class="btn btn-success"><i class="fa-solid fa-floppy-disk"></i> Submit</button>
    </form>
  
  </div>
</div>
@endsection

resources/views/items/edit.blade.php

@extends('items.layout')

@section('content')

<div class="card mt-5">
  <h2 class="card-header">Edit Item</h2>
  <div class="card-body">
  
    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
        <a class="btn btn-primary btn-sm" href="{{ route('items.index') }}"><i class="fa fa-arrow-left"></i> Back</a>
    </div>
  
    <form action="{{ route('items.update', $item->id) }}" method="POST">
        @csrf
        @method('PUT')
  
        <div class="mb-3">
            <label for="name" class="form-label"><strong>Name:</strong></label>
            <input 
                type="text" 
                name="name" 
                value="{{ $item->name }}"
                class="form-control @error('name') is-invalid @enderror" 
                id="name" 
                placeholder="Name">
            @error('name')
                <div class="form-text text-danger">{{ $message }}</div>
            @enderror
        </div>
  
        <div class="mb-3">
            <label for="detail" class="form-label"><strong>Detail:</strong></label>
            <textarea 
                class="form-control @error('detail') is-invalid @enderror" 
                style="height:150px" 
                name="detail" 
                id="detail" 
                placeholder="Detail">{{ $item->detail }}</textarea>
            @error('detail')
                <div class="form-text text-danger">{{ $message }}</div>
            @enderror
        </div>
        <button type="submit" class="btn btn-success"><i class="fa-solid fa-floppy-disk"></i> Update</button>
    </form>
  
  </div>
</div>
@endsection

resources/views/items/show.blade.php

@extends('items.layout')

@section('content')

<div class="card mt-5">
  <h2 class="card-header">Show Item</h2>
  <div class="card-body">
  
    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
        <a class="btn btn-primary btn-sm" href="{{ route('items.index') }}"><i class="fa fa-arrow-left"></i> Back</a>
    </div>
  
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong> <br/>
                {{ $item->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 mt-2">
            <div class="form-group">
                <strong>Details:</strong> <br/>
                {{ $item->detail }}
            </div>
        </div>
    </div>
  
  </div>
</div>
@endsection

 
Step 9: Run the Laravel 11 App

Run the following command to start the development server:

php artisan serve

Your Laravel application is now up and running, and you can start testing the CRUD operations you've implemented.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS