Laravel 11 Create CRUD Operation with Database

Websolutionstuff | Apr-08-2024 | Categories : Laravel PHP MySQL

Hello developers! In this article, we'll learn about Laravel 11 to create Creat Reas Update Delete operations with MySQL Database. Recently laravel 11 has been released with many new features and is more simple and straight.

Also, we'll cover installing laravel 11 and creating migration, models, and controllers with MySQL database. Also, we'll use Bootstrap 5 for layouts.

How to Create CRUD Operation in Laravel 11

Step 1: Installing Laravel 11

In this step, I'll install Laravel 11 using the following composer command.

composer create-project laravel/laravel laravel-11-crud

 

Step 2: MySQL Database Configuration

Then, we'll configure the database in 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

Next, we'll validate incoming requests using the following command.

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

Then, we'll create the Controller and Model in Laravel 11 with the help of artisan command.

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

Now, we'll define the resource routes in the web.php file.

routes/web.php

<?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

Next, we'll use Bootstrap 5 for laravel default pagination. So, define the useBootstrapFive() in the AppServiceProvider.php file.

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

Now, we'll create the 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>Laravel 11 Create CRUD Operation with Database - Websolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/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 Create CRUD Operation with Database - Websolutionstuff</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

Now, Run the following command to start the development server:

php artisan serve

Thanks for the reading..!

 


You might also like:

Recommended Post
Featured Post
How to Create New Component in Angular 17 using Command
How to Create New Component in...

Welcome to this comprehensive tutorial where I'll guide you through the process of creating a new component in Angul...

Read More

Mar-22-2024

How To File Upload In React JS
How To File Upload In React JS

In this article, we will see how file uploads in react js. File uploading means a user from a client machine wants...

Read More

Sep-05-2022

Laravel 6/7 CRUD tutorial with example
Laravel 6/7 CRUD tutorial with...

In this example, I will show you how to make simple laravel CRUD(insert, update, delete, or list) operations with e...

Read More

May-08-2020

How To Get The ID Of An Element Using jQuery
How To Get The ID Of An Elemen...

In this article, we will see how to get the id of an element using jquery. Using the jquery attr() method to get or...

Read More

Jul-04-2022