Laravel CRUD

Laravel CRUD

Laravel is a powerful PHP framework that simplifies web development with built-in support for Create, Read, Update, and Delete (CRUD) operations. This guide demonstrates how to implement CRUD functionality in Laravel with small descriptions for each step.

1. Setting Up Laravel

Before implementing CRUD, ensure your Laravel project is properly set up.

Installation

bash

composer create-project laravel/laravel laravel-crud-app
cd laravel-crud-app
php artisan serve

Database Configuration

Update .env with your database settings. Assuming you use locally hosted MySQL database:

env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_crud
DB_USERNAME=root
DB_PASSWORD=


Run database migrations:

bash

php artisan migrate

2. Defining the Model and Migration

A model represents a database table, and migrations are operations to define its schema.

Create a Model and Migration

bash

php artisan make:model User -m

Edit the Migration File (database/migrations/xxxx_xx_xx_create_users_table.php)

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->boolean('active')->default(true);
        $table->timestamps();
    });
}

Run Migration

bash

php artisan migrate

3. Creating a Controller and Routes

A controller handles client’s HTTP requests, and routes define API endpoints.

Generate a Controller

bash

php artisan make:controller UserController --resource

Define Routes (routes/web.php)

use App\Http\Controllers\UserController;

Route::resource('users', UserController::class);

4. Implementing CRUD Operations

Create (POST)

The store method saves new data to the database.

Controller (app/Http/Controllers/UserController.php)

public function store(Request $request)
{
    $request->validate([
        'name' => 'required',
        'email' => 'required|email|unique:users',
    ]);

    $user = User::create($request->all());
    return redirect()->route('users.index')->with('success', 'User created successfully.');
}

Form View (resources/views/users/create.blade.php)

<form action="{{ route('users.store') }}" method="POST">
    @csrf
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <button type="submit">Create</button>
</form>


Read (GET)

The index and show methods retrieve all or specific records.

Controller

public function index()
{
    $users = User::all();
    return view('users.index', compact('users'));
}

public function show(User $user)
{
    return view('users.show', compact('user'));
}


Table View (resources/views/users/index.blade.php)

<table>
    <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Actions</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ $user->email }}</td>
        <td>
            <a href="{{ route('users.show', $user->id) }}">View</a>
            <a href="{{ route('users.edit', $user->id) }}">Edit</a>
            <form action="{{ route('users.destroy', $user->id) }}" method="POST" style="display:inline;">
                @csrf @method('DELETE')
                <button type="submit">Delete</button>
            </form>
        </td>
    </tr>
    @endforeach
</table>


Update (PUT/PATCH)

The update method modifies an existing record.

Controller

public function update(Request $request, User $user)
{
    $request->validate([
        'name' => 'required',
        'email' => 'required|email|unique:users,email,' . $user->id,
    ]);

    $user->update($request->all());
    return redirect()->route('users.index')->with('success', 'User updated successfully.');
}


Form View (resources/views/users/edit.blade.php)

<form action="{{ route('users.update', $user->id) }}" method="POST">
    @csrf @method('PUT')
    <input type="text" name="name" value="{{ $user->name }}" required>
    <input type="email" name="email" value="{{ $user->email }}" required>
    <button type="submit">Update</button>
</form>


Delete (DELETE)

The destroy method removes a record from the database.

Controller

public function destroy(User $user)
{
    $user->delete();
    return redirect()->route('users.index')->with('success', 'User deleted successfully.');
}

Delete Button in View

<form action="{{ route('users.destroy', $user->id) }}" method="POST">
    @csrf @method('DELETE')
    <button type="submit">Delete</button>
</form>

5. Laravel API CRUD

For API-based CRUD, use Laravel’s API resources.

API Routes (routes/api.php)

use App\Http\Controllers\UserController;

Route::apiResource('users', UserController::class);

Example API Response

{
  "id": 1,
  "name": "John Doe",
  "email": "john.doe@example.com",
  "active": true
}

Examples of Open-Source Laravel CRUD Projects