CRUD Operations in Laravel 9 – A comprehensive guide

crud operations in laravel

CRUD Operations in Laravel: step by step

Laravel is a powerful and popular PHP framework known for its elegant syntax and extensive features. One of its key strengths lies in its ability to simplify the process of performing CRUD operations (Create, Read, Update, Delete) on a database. In this ultimate guide, we will explore the fundamental concepts and techniques for performing CRUD operations with Laravel.

1. Setting Up Laravel:

Before diving into CRUD operations, you need to set up a Laravel project. Install Laravel globally on your system, create a new project, and configure the database connection in the .env file. Laravel provides a built-in ORM (Object-Relational Mapping) called Eloquent, which makes interacting with the database effortless.

2. Creating a Database Table:

To perform CRUD operations, you need a database table. Use Laravel’s migration feature to create a migration file and define the table structure. Migrations allow you to version control your database schema and easily share it with your team.

3. Creating Records (Create):

Laravel provides an intuitive way to create new records in the database. Utilize the Eloquent model to define the structure and relationships of your table. Then, use the model’s create method to insert new records. Laravel takes care of generating the necessary SQL queries for you.

4. Retrieving Records (Read):

Reading data from the database is a common task in any application. Laravel offers several methods for retrieving records, such as the find method, where method, and more. You can also apply conditions, sorting, and pagination to your queries to fetch the desired data efficiently.

5. Updating Records (Update):

Updating existing records is straightforward with Laravel. Once you retrieve a record, you can modify its attributes and call the save method on the model. Alternatively, you can use the update method to update multiple records at once, based on specific criteria.

6. Deleting Records (Delete):

Laravel simplifies the process of deleting records from the database. By calling the delete method on the model instance, you can remove a single record. Additionally, you can use the destroy method to delete multiple records at once, based on their IDs.

7. Form Validation:

When performing CRUD operations, it is crucial to validate user input to ensure data integrity. Laravel provides a powerful validation system that allows you to define validation rules for your input fields. By utilizing Laravel’s validation features, you can easily validate user input before performing database operations.

8. Flash Messages and Error Handling:

Displaying flash messages and handling errors gracefully are important aspects of any CRUD application. Laravel offers a session-based flash messaging system, allowing you to store messages temporarily and display them to users. Additionally, Laravel provides robust error handling mechanisms, including exception handling, to ensure your application remains stable and user-friendly.

9. Authentication and Authorization:

In many cases, you need to restrict CRUD operations based on user roles and permissions. Laravel provides a robust and all-inclusive authentication and authorization system by default. You can utilize Laravel’s middleware and policies to control access to your CRUD operations routes and ensure that only authorized users can perform certain actions.

By following this ultimate guide, you’ll have a solid understanding of performing CRUD operations with Laravel. Laravel’s simplicity and expressive syntax, combined with its rich ecosystem, make it an excellent choice for building powerful and scalable applications. Start exploring Laravel’s CRUD capabilities, and unleash your potential to create amazing web applications.

CRUD operations in Laravel, HTML, CSS form and table with a controller, including creating the database table using migration:

Step 1: Create a new Laravel project:

laravel new crud-app
cd crud-app

Step 2: Create the database
Create a new database in MySQL or any other database management system.

Step 3: Configure the .env file
Open the .env file located at the root directory of your project and update the database connection details:

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 4: Create the model:
In Laravel, you can create an Eloquent model by running the following command:

php artisan make:model Book -m

This will create a new Book.php model and a migration file for creating the books table.

Step 5: Define the fields
In the migration file, define the fields that should be in your database table:

Create a book table in your database to store user credentials. Run the following migration command to create the table:

php artisan make:migration create_book_table --create=book
public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->string('author');
        $table->text('description');
        $table->timestamps();
    });
}

Step 6: Run the migration to create the table
Run the migration command to create the books table:

php artisan migrate

Step 7: Create the controller
Create a new controller called BookController with the following command:

php artisan make:controller BookController --resource

The --resource flag creates a RESTful resource controller with CRUD operations.

Step 8: Define the routes
In routes/web.php file, define the routes for CRUD operations:

Route::get('/books', [App\Http\Controllers\BookController::class, 'index'])->name('books.index');
Route::get('/books/create', [App\Http\Controllers\BookController::class, 'create'])->name('books.create');
Route::post('/books',[App\Http\Controllers\BookController::class, 'store'])->name('books.store');
Route::get('/books/{id}',[App\Http\Controllers\BookController::class, 'show'])->name('books.show');
Route::get('/books/{id}/edit', [App\Http\Controllers\BookController::class, 'edit'])->name('books.edit');
Route::put('/books/{id}', [App\Http\Controllers\BookController::class, 'update'])->name('books.update');
Route::delete('/books/{id}',[App\Http\Controllers\BookController::class, 'destroy'] )->name('books.destroy');

// OR this also works the same way

Route::resource('books', BookController::class);

index function to show all records:

public function index()
{
    $books = Book::all();

    return view('books.index', compact('books'));
}

Step 9: Create the views

Create the following view files in the resources/views/books folder:

  • index.blade.php – to display all books
  • create.blade.php – to create a new book
  • edit.blade.php – to edit an existing book
  • show.blade.php – to show details of a single book

Create app.blade.php view file in the resources/view/layouts

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{ config('app.name', 'Laravel') }}</title>
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>
    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
      integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
      crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
      integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
      crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
      integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaSfGasS7UFn6Gg8jXRMQVxMfooAo"
      crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
      integrity="sha384-35qyI9T24zMgJODsGIOqaB/gRVZE3XnKPEnTM2Kd3YB1nz2gxhJ7o5w8EX6kFJQV"
      crossorigin="anonymous"></script>
    
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse"
                    data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav me-auto">
                    </ul>
                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ms-auto">
                        <!-- Authentication Links -->
                        @guest
                            @if (Route::has('login'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                                </li>
                            @endif
                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                </li>
                            @endif
                        @else
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button"
                                    data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }}
                                </a>
                                <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                        onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>
                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>
        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>

A sample create.blade.php file looks like this:

@extends('layouts.app')
@section('content')
    <h1>Add New Book</h1>
    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
<h3 class="text-center">ALgocodersmind|CRUD in laravel</h3>
    <form method="POST" action="{{ route('books.store') }}">
        @csrf
        <div class="form-group">
            <label for="title">Title:</label>
            <input type="text" name="title" class="form-control" id="title">
        </div>
        <div class="form-group">
            <label for="author">Author:</label>
            <input type="text" name="author" class="form-control" id="author">
        </div>
        <div class="form-group">
            <label for="description">Description:</label>
            <textarea name="description" class="form-control" id="description"></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Add Book</button>
  <a href="{{route('books.index')}}"  class="btn btn-dark">Back</a>
    </form>
@endsection

Step 10: Write the CRUD methods in the controller
In the BookController file, define the CRUD operations for your application. Here’s an example of the store() method:

public function store(Request $request)
{
    // Validate the form data
    $validatedData = $request->validate([
        'title' => 'required|max:255',
        'author' => 'required|max:255',
        'description' => 'required',
    ]);

    // Create a new book
    $book = new Book();
    $book->title = $validatedData['title'];
    $book->author = $validatedData['author'];
    $book->description = $validatedData['description'];
    $book->save();

    // Redirect to the books index page with a success message
    return redirect()->route('books.index')->with('success', 'Book created successfully.');
}

Create() method to load view form

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

Step 11: Update the Form and Controller

Update the editable fields and their respective CRUD functions in the controller below:
edit.blade.php

@extends('layouts.app')

@section('content')
    <h1>Edit Book</h1>
    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    <form method="POST" action="{{ route('books.update', ['id' => $book->id]) }}">
        @csrf
        @method('PUT')
        <div class="form-group">
            <label for="title">Title:</label>
            <input type="text" name="title" class="form-control" id="title" value="{{ $book->title }}">
        </div>
        <div class="form-group">
            <label for="author">Author:</label>
            <input type="text" name="author" class="form-control" id="author" value="{{ $book->author }}">
        </div>
        <div class="form-group">
            <label for="description">Description:</label>
            <textarea name="description" class="form-control" id="description">{{ $book->description }}</textarea>
        </div>
        <button type="submit" class="btn btn-primary">Update Book</button>
  <a href="{{route('books.index')}}"  class="btn btn-dark">Back</a>
    </form>
@endsection

The updated edit() method in the controller looks like this:

public function edit($id)
{
   $book = Book::find($id);
   return view('books.edit', compact('book'));
}

Update recode using update() method in controller looks like this:

public function update(Request $request, Book $book)
{
    $validatedData = $request->validate([
        'title' => 'required|max:255',
        'author' => 'required|max:255',
        'description' => 'required',
    ]);

    $book->update($validatedData);

    return redirect()->route('books.show', ['book' => $book]);
}

Step 11: Add Delete Functionality

To add delete functionality, simply add the following code to your index view file:

<td>
    <a href="{{ route('books.show', ['id' => $book->id]) }}" class="btn btn-sm btn-success">View</a>
    <a href="{{ route('books.edit', ['id' => $book->id]) }}" class="btn btn-sm btn-primary">Edit</a>
    <form method="POST" action="{{ route('books.destroy', ['id' => $book->id]) }}" style="display: inline-block">
        @csrf
        @method('DELETE')
        <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')">Delete</button>
    </form>
</td>

And then define the destroy() method in your controller:

public function destroy($id)
{
    // Get the book
    $book = Book::find($id);

    // Delete the book
    $book->delete();

    // Redirect to the books index page with a success message
    return redirect()->route('books.index')->with('success', 'Book deleted successfully.');
}

index.blade.php file for displaying all books in a table:

@extends('layouts.app')
@section('content')
    <h1>Books</h1>
    @if (session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif
    <h3 class="text-center">ALgocodersmind|CRUD in laravel</h3>
    <a href="{{ route('books.create') }}" class="btn btn-primary mb-2">Add New Book</a>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Author</th>
                <th>Description</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($books as $book)
                <tr>
                    <td>{{ $book->id }}</td>
                    <td>{{ $book->title }}</td>
                    <td>{{ $book->author }}</td>
                    <td>{{ $book->description }}</td>
                    <td>
                        <a href="{{ route('books.show', ['id' => $book->id]) }}" class="btn btn-sm btn-success">View</a>
                        <a href="{{ route('books.edit', ['id' => $book->id]) }}" class="btn btn-sm btn-primary">Edit</a>
                        <form method="POST" action="{{ route('books.destroy', ['id' => $book->id]) }}" style="display: inline-block">
                            @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>
@endsection

View record in show.blade.php

@extends('layouts.app')

@section('content')
    <div class="container">
        <h1>{{ $book->title }}</h1>
        <p><strong>Author:</strong> {{ $book->author }}</p>
        <hr>
        <p>{{ $book->description }}</p>
        <hr>
        <a href="{{ route('books.edit', $book->id) }}" class="btn btn-primary">Edit</a>
        <form action="{{ route('books.destroy', $book->id) }}" method="POST" style="display:inline-block;">
            @csrf
            @method('DELETE')
            <button type="submit" class="btn btn-danger">Delete</button>
        </form>
    </div>
@endsection
BookController.php
<?php

namespace App\Http\Controllers;

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

class BookController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $books = Book::all();

        return view('books.index', compact('books'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
     return view('books.create');
   }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
{
    // Validate the form data
    $validatedData = $request->validate([
        'title' => 'required|max:255',
        'author' => 'required|max:255',
        'description' => 'required',
    ]);
    // Create a new book
    $book = new Book();
    $book->title = $validatedData['title'];
    $book->author = $validatedData['author'];
    $book->description = $validatedData['description'];
    $book->save();
    // Redirect to the books index page with a success message
    return redirect()->route('books.index')->with('success', 'Book created successfully.');
}

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $book = Book::find($id);
        return view('books.show', compact('book'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
       $book = Book::find($id);
       return view('books.edit', compact('book'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id, Book $book)
    {
        $validatedData = $request->validate([
            'title' => 'required|max:255',
            'author' => 'required|max:255',
            'description' => 'required',
        ]);
      $book = Book::find($id); 
      $bookData = [
          'title' => $request->title,
          'author' => $request->author,
          'description' => $request->description,
      ];
      $book->update($bookData);
      
       return redirect()->route('books.index');
       
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        // Get the book
        $book = Book::find($id);
        // Delete the book
        $book->delete();
        // Redirect to the books index page with a success message
        return redirect()->route('books.index')->with('success', 'Book deleted successfully.');
    }
}

Output images:

CRUD Operations in Laravel

That’s it! You now have a fully-functional CRUD operations in Laravel, HTML, CSS form and table with a controller. You can repeat these steps for any other resource you want to manage in your application.


Our Recommendation

Avatar of Akhand Pratap Singh

Akhand Pratap Singh

Greetings and a warm welcome to my website! I am Akhand Pratap Singh, a dedicated professional web developer and passionate blogger.

Related Post

Leave a Comment





Newsletter

Subscribe for latest updates

We don't spam.

Loading

Categories