Laravel 8 CRUD Operation with example from the scratch

Hello Devs, 

CRUD operation is a basic functionality in any web application. To manage in admin panel, there must be CRUD operation required.

Today in this post we will share you how to implement CRUD operation in Laravel 8 application from the scratch. Follow the below steps to implement CRUD operation.

  • Step  1. Create new Laravel project
  • Step  2. Configure database environment
  • Step  3. Run migration and database tables
  • Step  4. Create routes
  • Step  5. Create controller class
  • Step  6. Create blade view files.

SO, let's get started.

Step 1. Create fresh Laravel project

First open the CMD or Terminal and create Laravel project using below command.

composer create-project --prefer-dist laravel/laravel users

Don't forget to change the working directory into Terminal.

cd users

Step 2. Configure database environment

Open the .env envirnment file and change the database with your MySQL database and credentials.

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

Step 3. Run migration and database tables

Now open the /database/migrations/2014_10_12_000000_create_users_table.php. You can modify the table fields according to your requirement. We will keep the as it is to make tutorial simple.

Now run the migration to generate database tables.

php artisan migrate

Step 4. Create new routes

Now create new resource route in routes/web.php file.

<?php

use Illuminate\Support\Facades\Route;
Use App\Http\Controllers\UserController;

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

Step 5. Create controller class

Create controller file to handle the routes.

php artisan make:controller UserController --resource

This will create controller file at /app/Http/Controllers/UserController.php. This is resource controller so you already have below methods defined for different operations.

Method      Url    Action    Route Name
GET       /users    index    users.index
GET      /users/create    create    users.create
POST    /users    store    users.store
GET    /users/{id}    show    users.show
GET     /users/{id}/edit    edit    users.edit
PUT/PATCH    /users/{id}    update    users.update
DELETE    /users/{id}    destroy    users.destroy

Add the codes for each methods.

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::orderBy('id', 'desc')
            ->get();

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('users.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->except(['_token', '_method']);

        $validated = $request->validate([
            'name' => 'required',
            'email' => 'required|unique:users|email',
            'password' => 'required|confirmed',
        ]);

        $input['password'] = Hash::make($input['password']);

        User::create($input);

        return redirect()->route('users.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $user = User::find($id);

        return view('users.show', compact('user'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = User::find($id);

        return view('users.edit', compact('user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $input = $request->except(['_token', '_method']);

        $validated = $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required|confirmed',
        ]);

        $input['password'] = Hash::make($input['password']);

        User::where('id', $id)
            ->update($input);

        return redirect()->route('users.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        User::find($id)
            ->delete();

        return redirect()->route('users.index');
    }
}

Your User model file is at app/Models/User.php. Make sure the fields you are updating should be in $fillable array in the model.

protected $fillable = [
    'name',
    'email',
    'password',
];

Step 6. Create blade files

Now we need to create view files to show and handle the data. Create View file at /resource/views/users/ folder.

index.blade.php - show list for users
show.blade.php - show specific user
create.blade.php - create user
edit.blade.php - edit user

Now add the HTML code for each files.

index.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Users</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row m-3">
            <div class="mb-3">
                <a href="{{ route('users.create') }}" class="btn btn-success">Create new user</a>
            </div>
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Name</th>
                        <th scope="col">Email</th>
                        <th scope="col">Action</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse ($users as $user)
                        <tr>
                            <th scope="row">{{ $loop->index + 1 }}</th>
                            <td>{{ $user->name }}</td>
                            <td>{{ $user->email }}</td>
                            <td>
                                <a href="{{ route('users.show', $user->id) }}" class="btn btn-primary m-1">Show</a>
                                <a href="{{ route('users.edit', $user->id) }}" class="btn btn-primary m-1">Edit</a>
                                <a href="#" class="btn btn-danger m-1" onclick="document.getElementById('delete-user-{{ $user->id }}').submit();">Delete</a>
                                <form method="post" action="{{ route('users.destroy', $user->id) }}" id="delete-user-{{ $user->id }}" style="display: none;">
                                    @csrf
                                    @method('DELETE')
                                </form>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="4" class="text-center">No users found.</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>

show.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Users</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="my-3">
                <ul class="list-group">
                    <li class="list-group-item">Name: {{ $user->name }}</li>
                    <li class="list-group-item">EMail: {{ $user->email }}</li>
                </ul>
            </div>
            <div class="mt-3">
                <a href="{{ route('users.index') }}" class="btn btn-warning">Back</a>
            </div>
        </div>
    </div>
</body>
</html>

create.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Users</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row m-3">
            <form method="post" action="{{ route('users.store') }}">
                @csrf
                <div class="mb-3">
                    <label class="form-label" for="name">Name</label>
                    <input type="text" name="name" class="form-control">
                    @error('name')
                        <div class="alert alert-danger">{{ $message }}</div>
                    @enderror
                </div>
                <div class="mb-3">
                    <label class="form-label" for="email">Email</label>
                    <input type="email" name="email" class="form-control">
                    @error('email')
                        <div class="alert alert-danger">{{ $message }}</div>
                    @enderror
                </div>
                <div class="mb-3">
                    <label class="form-label" for="password">Password</label>
                    <input type="password" name="password" class="form-control">
                    @error('password')
                        <div class="alert alert-danger">{{ $message }}</div>
                    @enderror
                </div>
                <div class="mb-3">
                    <label class="form-label" for="password_confirmation">Confirm Password</label>
                    <input type="password" name="password_confirmation" class="form-control">
                </div>
                <input type="submit" class="btn btn-success">
                <a href="{{ route('users.index') }}" class="btn btn-warning">Back</a>
            </form>
        </div>
    </div>
</body>
</html>

edit.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Users</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row m-3">
            <form method="post" action="{{ route('users.update', $user->id) }}">
                @csrf
                @method('PATCH')
                <div class="mb-3">
                    <label class="form-label" for="name">Name</label>
                    <input type="text" name="name" value="{{ $user->name }}" class="form-control">
                    @error('name')
                        <div class="alert alert-danger">{{ $message }}</div>
                    @enderror
                </div>
                <div class="mb-3">
                    <label class="form-label" for="email">Email</label>
                    <input type="email" name="email" value="{{ $user->email }}" class="form-control">
                    @error('email')
                        <div class="alert alert-danger">{{ $message }}</div>
                    @enderror
                </div>
                <div class="mb-3">
                    <label class="form-label" for="password">Password</label>
                    <input type="password" name="password" class="form-control">
                    @error('password')
                        <div class="alert alert-danger">{{ $message }}</div>
                    @enderror
                </div>
                <div class="mb-3">
                    <label class="form-label" for="password_confirmation">Confirm Password</label>
                    <input type="password" name="password_confirmation" class="form-control">
                </div>
                <input type="submit" class="btn btn-success">
                <a href="{{ route('users.index') }}" class="btn btn-warning">Back</a>
            </form>
        </div>
    </div>
</body>
</html>

Now run the Laravel server

php artisan serve

Open your browser and go to http://localhost:8000/users.

Conclusion

So this way, you can implement the CRUD operation in your Laravel application. I hope you liked this article.