Laravel 8 CRUD example - Step by step

Laravel 8 CRUD example - Step by step

 


CRUD (Create, Read, Update, Delete) operations are essentials for learning Laravel.

In this article, we will learn CRUD operations step by step in Laravel 8 from scratch.

Table of Contents

1) Create Project in Laravel

Create a project using the following command. It will create a project with the name Laravel-crud. You can replace Laravel-crud with your project name.

Requirements:

  • php version : 7.3.* +
php -v

If the requirement is fulfilled then set up a project or create a project using the below command.

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

2) Setup MySql database

Now, create a database. I have created a database named Laravel-crud in PHPMyAdmin. To configure this database with our project we have to make a few changes in .env file. So, database configurations in my .env file are as following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-crud  #your database name
DB_USERNAME=root          #your database username
DB_PASSWORD=              #your database password

Make sure to change these configurations as per your database and don’t forget to restart the server.

3) Create Migration

In this article, we are going to create a crud application for employees. So, let’s create a migration for the employees’ table.

To create a migration, use the make:migration Artisan command:

php artisan make:migration create_employees_table --create=employees

Here --create the option is optional, it may be used to indicate the name of the table.
--create will pre-fill the generated migration file with the specified table name.

After running the above command you will find a new migration file in database/migrations the directory.

A migration class contains up() and down() methods:

  • up() is used to add new tables, columns, or indexes to a database.
  • down() is used to reverse the operations performed by the up() method.

In Up() Schema::create() is used to create a table.

The first parameter of Schema::create() is the name of the table and the second parameter is a callback function.

A callback function has a $table->bigIncrements('id') and $table->timestamps():

  • $table->timestamps() will create two columns created_at and updated_at with type timestamp.

To add more columns in the employees’ table we have to write them inside up() as following

<?php

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

class CreateEmployeesTable extends Migration
{
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->integer('age');
            $table->integer('salary');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('employees');
    }
}

Now run the migration using the following command to create a table:

php artisan migrate

To roll back this migration operation, you may use the migrate:rollback command as follows:

php artisan migrate:rollback

4) Create Model

To create a model in Laravel make:model artisan command is used.

Here we need to create a model for the employees’ table. So we will create a model named Employee as follows:

php artisan make:model Employee

After running the above command you will find an Employee model in app directory.

Add $fillable property inside the Employee.php file. $fillable the property contains attributes that are mass assignable.

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    use HasFactory;
    protected $fillable = ["name", "email", "age", "salary"];
}

5) Create Controller and Routes

In this tutorial, we will use resource controllers and routes. Laravel resource routing assigns the typical CRUD routes to a controller with a single line of code.

we can create a resource controller using the make:controller command with -r or --resource flag.

php artisan make:controller EmployeeController --resource

The above command will generate EmployeeController.php file inside app/Http/Controllers directory.

Because of --resource flag 7 methods will be generated inside our controller:

  • index(): Used to display a listing of the records.
  • create(): Used to show a form for creating a new record.
  • store(Request $request): Used to store a newly created record inside the database.
  • show($id): Used to Display the specified record.
  • edit($id): Used to show a form for editing a specified record.
  • update(Request $request, $id): Used to update the specified record inside the database.
  • destroy($id): Used to delete a specified record from the database.

After creating a resourceful controller now we will create resourceful routes for it.

To create resourceful routes just add the following line of code inside your routes/web.php file.

Route::resource('employees', 'EmployeeController');

The above code will generate the following routes for EmployeeController

MethodURIActionName
GET/employeesindexemployees.index
GET/employees/createcreateemployees.create
POST/employeesstoreemployees.store
GET/employees/{employee}showemployees.show
GET/employees/{employee}/editeditemployees.edit
PUT/PATCH/employees/{employee}updateemployees.update
DELETE/employees/{employee}destroyemployees.destroy

We can see the list of all available routes in our project by using the following command.

php artisan route:list

6) Configure Bootstrap

To configure bootstrap first we need to install laravel/ui package. Use the following command to install laravel/ui package:

composer require laravel/ui

After installing laravel/ui package use the following command to install bootstrap:

php artisan ui bootstrap

By running the above command, Bootstrap scaffolding will be installed successfully. To compile that scaffolding please run the following commands:

npm install 

npm run dev

Now you can see bootstrap 4 inside your public\css\app.css file.

file_structure of laravel
File Structure

7) Create the Layout

Now, create a layout.blade.php file inside resources\views directory as follows:

resources\views\layout.blade.php :

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 8 CRUD @ coding-notes.com</title>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>

<body>

    <div class="container">
        @yield('content')
    </div>

    <script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>

</html>

This layout file will be used in each view files.

8) Implement the Create Operation

Create an employees directory inside resources\views and create create.blade.php file inside that employees directory.

Now, return the view from create() of EmployeeController.php as follows.

app\Http\Controllers\EmployeeController.php :

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

To create a form for collecting data write the following code inside the create.blade.php:

resources\views\employees\create.blade.php :

@extends('layout')

@section('content')
<div class="row justify-content-center mt-4">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header text-center">Create Employee</div>
            <div class="card-body">
                <form method="POST" action="{{route('employees.store')}}">
                    @csrf

                    <div class="form-group row">
                        <label for="name" class="col-md-4 col-form-label text-md-right">Name</label>
                        <div class="col-md-6">
                            <input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name') }}">
                            
                            @error('name')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </div>

                    <div class="form-group row">
                        <label for="email" class="col-md-4 col-form-label text-md-right">Email</label>
                        <div class="col-md-6">
                            <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}">

                            @error('email')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </div>

                    <div class="form-group row">
                        <label for="age" class="col-md-4 col-form-label text-md-right">Age</label>
                        <div class="col-md-6">
                            <input id="age" type="text" class="form-control @error('age') is-invalid @enderror" name="age" value="{{ old('age') }}">

                            @error('age')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </div>

                    <div class="form-group row">
                        <label for="salary" class="col-md-4 col-form-label text-md-right">Salary</label>
                        <div class="col-md-6">
                            <input id="salary" type="text" class="form-control @error('salary') is-invalid @enderror" name="salary" value="{{ old('salary') }}">

                            @error('salary')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </div>

                    <div class="form-group row mb-0">
                        <div class="col-md-8 offset-md-4">
                            <a href="{{route('employees.index')}}" class="btn btn-outline-dark">
                                Cancle
                            </a>
                            <button type="submit" class="btn btn-primary">
                                Submit
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>    
@endsection

To store the form data into database write the following code inside the store() of EmployeeController.php.

app\Http\Controllers\EmployeeController.php :

public function store(Request $request)
{
$employeeData = $request->validate([
'name' => 'required',
'email' => 'required',
'age' => 'required',
'salary' => 'required'
]);

Employee::create($employeeData);
return redirect('employees')->with('success', 'Employee create successfully.');
}

9) Implement the Read Operation

create an index.blade.php file inside the employees directory to display the data of employees table.

Now, write the following code inside the index() of EmployeeController.php to get the data of all employees.

app\Http\Controllers\EmployeeController.php :

public function index()
{
$employees = Employee::all();

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

write the following code inside the index.blade.php display the employees’ data.

resources\views\employees\index.blade.php :

@extends('layout')

@section('content')
<div class="row mt-4">
<div class="col-md-12">
@if(session()->get('success'))
<div class="alert alert-success my-3">
{{ session()->get('success') }}
</div>
@endif

<a href="{{route('employees.create')}}" class="btn btn-primary mb-4">Add Employee</a>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>ID</td>
<td>Employee Name</td>
<td>Employee Email</td>
<td>Employee Age</td>
<td>Employee Salary</td>
<td colspan="2">Actions</td>
</tr>
</thead>
<tbody>
@foreach($employees as $employee)
<tr>
<td>{{$employee->id}}</td>
<td>{{$employee->name}}</td>
<td>{{$employee->email}}</td>
<td>{{$employee->age}}</td>
<td>{{$employee->salary}}</td>
<td><a href="{{ route('employees.edit', $employee->id)}}" class="btn btn-primary">Edit</a></td>
<td>
<form action="{{ route('employees.destroy', $employee->id)}}" method="post">
@csrf
@method('DELETE')
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<div>
@endsection

10) Implement the Update Operation

Create edit.blade.php file inside the employees directory to create a form for editing the employees’ data.

Now, write the following code inside the edit() of EmployeeController.php to edit the data of specific employees.

app\Http\Controllers\EmployeeController.php :

public function edit($id)
{
$employee = Employee::findOrFail($id);

return view('employees.edit', compact('employee'));
}

To create a form for editing data of employee write the following code inside the edit.blade.php:

resources\views\employees\edit.blade.php :

@extends('layout')

@section('content')

<div class="row justify-content-center mt-4">
<div class="col-md-8">
<div class="card">
<div class="card-header text-center">Edit Employee</div>

<div class="card-body">
<form method="post" action="{{route('employees.update', $employee->id)}}">
@csrf
@method('PATCH')

<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">Name</label>

<div class="col-md-6">
<input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{$employee->name}}">

@error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>

<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email</label>

<div class="col-md-6">
<input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{$employee->email}}">

@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>

<div class="form-group row">
<label for="age" class="col-md-4 col-form-label text-md-right">Age</label>

<div class="col-md-6">
<input id="age" type="text" class="form-control @error('age') is-invalid @enderror" name="age" value="{{$employee->age}}">

@error('age')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>

<div class="form-group row">
<label for="salary" class="col-md-4 col-form-label text-md-right">Salary</label>

<div class="col-md-6">
<input id="salary" type="text" class="form-control @error('salary') is-invalid @enderror" name="salary" value="{{$employee->salary}}">

@error('salary')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>

<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<a href="{{route('employees.index')}}" class="btn btn-outline-dark">
Cancle
</a>
<button type="submit" class="btn btn-primary">
Update
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>

@endsection

To update employees’ data into database write the following code inside the update() of EmployeeController.php.

app\Http\Controllers\EmployeeController.php

public function update(Request $request, $id)
{
$employeeData = $request->validate([
'name' => 'required',
'email' => 'required',
'age' => 'required',
'salary' => 'required'
]);

$employee = Employee::findOrFail($id);
$employee->name = $request->name;
$employee->email = $request->email;
$employee->age = $request->age;
$employee->salary = $request->salary;
$employee->save();

return redirect('employees')->with("success", "Employees' details are updated successfully.");
}

11) Implement the Delete Operation

To delete a particular record write the following code inside the destroy() of EmployeeController.php.

app\Http\Controllers\EmployeeController.php :

public function destroy($id)
{
$employee = Employee::findOrFail($id);
$employee->delete();

return redirect('employees')->with("success", "Employee deleted successfully.");
}

12) EmployeeController.php

<?php
namespace App\Http\Controllers;

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

class EmployeeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $employees = Employee::all();

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

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

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $employeeData = $request->validate(['name' => 'required', 'email' => 'required', 'age' => 'required', 'salary' => 'required']);

        Employee::create($employeeData);
        return redirect('employees')->with('success', 'Employee create successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        
    }

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

        return view('employees.edit', compact('employee'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $employeeData = $request->validate(['name' => 'required', 'email' => 'required', 'age' => 'required', 'salary' => 'required']);

        $employee = Employee::findOrFail($id);
        $employee->name = $request->name;
        $employee->email = $request->email;
        $employee->age = $request->age;
        $employee->salary = $request->salary;
        $employee->save();

        return redirect('employees')
            ->with("success", "Employees' details are updated successfully.");
    }

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

        return redirect('employees')
            ->with("success", "Employee deleted successfully.");
    }
}

Now, you can run the application using php artisan serve command and see the output at http://127.0.0.1:8000/employees

Thus, we have created a complete Laravel CRUD application step-by-step from scratch.

Hope it will help you.

Reactions

Post a Comment

0 Comments