Back to Blog 10 min read

How to make CRUD In Laravel

Creating crud is the first step of starting with any backend framework or language. I will try to explain Laravel crud to you in very simple manner a...

Creating crud is the first step of starting with any backend framework or language. I will try to explain Laravel crud to you in very simple manner as much as I can. So without taking so much time let's learn together how we can create crud in Laravel.

Install Laravel

You all might know before starting anything you have to do install the laravel. Okay, First of all, let's install the Laravel.

composer create-project laravel/laravel crud

Now, when your project will be installed then start building your crud system.

Create a Database with the name "crud"

Setup .env File for database Connection

Now, we have to set up the .env file to interact/play with the database. This is the file where we do set up most of the configurations. For example SMTP.

set up connection with the database

After setting up this file you might know that we have to migrate the database. It's not necassery to migrate first you also can create a database without migration but doing and using migration is the best way to do that. For that, you have to run a command which is php artisan migrate.

After doing this you might have an error, You just need to copy that and put into the search of google you obviously will get solutions.

if you are a daily programmer then you can check this previous post.

Vs Code Extensions For Laravel Developers

It will help you.

Create View Files

Now, we are almost done with the initial steps, and let's start creating view files. So, that we can create a successful CRUD system.

In this Laravel CRUD, we just need three files. Create a folder in view with the name of the layout and create a file in this folder with the name app.blade.php

  • view/layout/app.blade.php
  • view/create.blade.php
  • view/users.blade.php
  • view/update.blade.php

Let's create a layout file

This layout file will be used everywhere in view. It depends on you if you want to repeat this code in each file then it's your decision.

app.blade.php

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>@yield('title')</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous">
    </script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

</head>

<body>
    @yield('content')
</body>
</html>

Create Listing Table

users.blade.php

@extends('layout.app')
@section('title','Users')
@section('content')
<div class="container">
    <div class="row py-5">
        <table class="table-light shadow-sm table">
            <a class="text-dark py-2" href="{{route('createusers')}}">Create New</a>
            <thead>
                <tr>
                    <th>Sr. No.</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Age</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                @if (!empty($users))
                @foreach ($users as $user)
                <tr>
                    <td>{{$loop->iteration}}</td>
                    <td>{{$user->name}}</td>
                    <td>{{$user->email}}</td>
                    <td>{{$user->age}}</td>
                    <td class="d-flex">
                        <a href="{{ route('editusers',[$user->id,$user->name,$user->email,$user->age])}}"
                            class="btn btn-sm btn-warning">Update</a>
                        <a href="{{route('deleteusers',['id'=>$user->id])}}" class="btn btn-sm btn-danger ms-2 delete">Delete</a>
                    </td>
                </tr>
                @endforeach
                @endif
            </tbody>
        </table>
        <div class="modal modal-sm deleteModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Modal title</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <p>Modal body text goes here.</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Save changes</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    $('.delete').on('click',function(){
        alert('Are you sure to delete this record');
    });
</script>
@endsection

Create a form

So, now we have to create a form for this we will use create.blade.php file. Let me just show you the code of the form.

create.blade.php

@extends('layout.app')
@section('title','create')
@section ('content')
<div class="container">
    <div class="row">
        @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
        @endif
        <form class="form" method="POST" action="{{route('storeusers')}}">
            @csrf
            <div class="mb-3">
                <label for="name" class="form-label">Name</label>
                <input type="text" class="form-control" id="name" name="name">
            </div>
            <div class="mb-3">
                <label for="email" class="form-label">Email address</label>
                <input type="email" class="form-control" id="email" name="email">
            </div>
            <div class="mb-3">
                <label for="age" class="form-label">Age</label>
                <input type="number" class="form-control" min="18" max="100" id="age" name="age">
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
</div>
@endsection

Create Update Form

@extends('layout.app')
@section('title','update')

@section('content')
    <div class="container">
        <div class="row py-4">
            @if ($errors->any())
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            @endif
            <form class="form" method="POST" action="{{route('updateusers')}}">
                @csrf
                <div class="mb-3">
                    <label for="name" class="form-label">Name</label>
                    <input type="text" class="form-control" id="name" value="{{$name}}" name="name">
                    <input type="hidden" value="{{$id}}" name="id">
                </div>
                <div class="mb-3">
                    <label for="email" class="form-label">Email address</label>
                    <input type="email" class="form-control" id="email" value="{{$email}}" name="email">
                </div>
                <div class="mb-3">
                    <label for="age" class="form-label">Age</label>
                    <input type="number" class="form-control" min="18" max="100" value="{{$age}}" id="age" name="age">
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
    </div>
@endsection

After writing the form code we have to write the functionality to save and update this form. So for that, we just need a controller to store the user credentials in the database. And we also need to create migration first. And after this migration, we will create a controller for each action.

migration

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name')->null;
            $table->string('email')->nullable();
            $table->integer('age')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Make Routes

Now we have all the blade files completed with HTML and bootstrap code. Now, let's make routes for all destinations.

routes/web.php

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::view('/users/create', 'create')->name('createusers');
Route::get('/users/edit/{id?}/{name?}/{email?}/{age?}', function($id,$name=null,$email=null,$age=null){
    return view('update',['id' => $id,'name'=>$name,'email'=>$email,'age'=>$age]);
})->name('editusers');
Route::get('/users', [UserController::class, 'show'])->name('showusers');
Route::post('/users/store', [UserController::class, 'store'])->name('storeusers');
Route::post('/users/update', [UserController::class, 'update'])->name('updateusers');
Route::get('/users/delete/{id}', [UserController::class, 'delete'])->name('deleteusers');

Create Validation Request

Before storing the data into the database we also do use validations so first validate the form request by creating a request called UserRequest.

let's create a validation request -> php artisan make:request UserRequest

You can check the Request folder in http folder. So, after that, we will use the name of the form inputs and validate them with desired validations. Let's see the code.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
          'name'  =>'required|string',
          'email'  =>'required',
          'age'  =>'required|numeric'
        ];
    }
}

Create Controller

After creating the request, we have to create a controller file in which we will interact with the modal or database. So, that we can perform the crud actions easily.

php artisan make:controller UserController

Now, we are into the controller and just store the created form in the database with the help of this controller. And wait,

now, create all the methods in the controller file for crud. Let's see the code.

UserController

<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserRequest;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function show()
    {
        $users = User::all();
        return view('users', compact('users'));
    }
    public function store(UserRequest $request)
    {
        $validated = $request->validated();
        $store = User::create($validated);
        return redirect()->route('showusers');
    }
    public function update(UserRequest $request)
    {
        $validated = $request->validated();
        $user = User::where('id', $request->id)->update($validated);
        return redirect()->route('showusers');
    }
    public function delete(Request $request)
    {
        User::where('id', $request->id)->delete();
        return back();
    }
}

Model Changes

After doing all this stuff you will have a model already if not you can create a model just by using this command php artisan make:model User and then you have to use these fillable fields in your model.

 protected $fillable = [
        'id',
        'name',
        'email',
        'age',
    ];

Conclusion

Now, we have done with all functionality. And I personally learned a lot of things when I was writing the code for this blog. I hope you will get your queries solved.

If you have any other questions please don't forget to type them into the comment box.

You also can check this code on Github - Laravel Crud