Laravel 8 CRUD Operations Tutorial

By: Suriyal

Laravel 8 CRUD tutorial with Bootstrap 5 and Font Awesome 6

Overview

In this Laravel 8 CRUD tutorial we are creating crud application using Laravel 8. We are using Bootstrap 5 and Font Awsome in this tutorial for front end design and icons. This is very helpful tutorial for beginners and who are new to Laravel.

Do you have the following questions ? If Yes, Keep reading this tutorial…

  1. How to install Laravel 8
  2. How to create Laravel 8 project
  3. How to connect Laravel application with MySQL
  4. How to create Model in Laravel
  5. How to create Controller in Laravel
  6. How to create Model and Migration using single command
  7. How to create Route in Laravel
  8. How to start XAMP, Apache & MySQL
  9. How to open Php MyAdmin
  10. How to create MySQL Database
  11. How to create Migration
  12. How to modify migration file
  13. How to run migration
  14. Create, Read, Update and Delete records from Database
  15. How to open visual code from start menu and command prompt
  16. How to open and use Laravel project in visual studio code
  17. How to create blade files
  18. How to run Laravel project and view in browser
Table of Contents

    We are using window operating system for this tutorial and have installed the following software / applications in our systems. Please ensure that your system is ready to create the Laravel applications. We are using XAMP.

    1. XAMP (Apache , MariaDB , MySQL , PHP , Perl)

    2. Composer

    3 .VS Code (you can use any other code editors of your choice)

    4. Bootstrap 5 with compiled CSS and JavaScript

    Glimpse

    laravel-8-crud-tutorial-with-bootstrap-5
    laravel-8-crud-tutorial-with-bootstrap-5
    laravel-8-crud-tutorial-with-bootstrap-5
    laravel-8-crud-tutorial-with-bootstrap-5
    laravel-8-crud-tutorial-with-bootstrap-5

    Install Laravel & Create Laravel 8 CRUD Tutorial Project

    1. Go to C:\xampp\htdocs\ and create one folder (name it Laravel or any name of your choice) for Laravel projects.  

    C:\xampp\htdocs\laravel

    Note: You can create Laravel projects directly in C:\xampp\htdocs I am creating a Laravel folder for my understanding only.

    2. Open command prompt and go the path C:\xampp\htdocs\laravel to create the Laravel project. The following command will install and create the Laravel project.

    Enter the following command and press enter

    Composer create-project –prefer-dist laravel/laravel EmployeeCRUD 

    Once the projected is created successfully open that in VSCode

    Open the project in VSCode

    You can directly open the VSCode or Visual Studio Code from start or can use command prompt.

    Method 1 – Open VSCode from Start menu

    1. Click on start menu and type VSCode and click on the VSCode app icon as shown in the following image

    Once VSCode is opened , do the followings

    1. Cick on the File menu
    2. Click on Open Folder (C:\xampp\htdocs\laravel\EmployeeCRUD)
    3. Go to the project directory (C:\xampp\htdocs\laravel\EmployeeCRUD)
    4. Select the project directory (C:\xampp\htdocs\laravel\EmployeeCRUD) and click on the select folder (you need not to open the folder, I have opened for demo purpose but this also works)

    Here is VSCode with you project

    Open VSCode from Command Prompt

    1 . Go to the project directory (C:\xampp\htdocs\laravel\EmployeeCRUD) 

    1. Once you are in the project directory C:\xampp\htdocs\laravel\EmployeeCRUD) 

     Type the following command and press enter

    Code .

    Here is VSCode with you project

    Start Apache and MySQL

    1. Click on start menu and type XAMP and click on the XAMP app icon

    2 . Click on the start button (Apache & MySQL

    Both Apache and MySql are running now

    Create Database

    Open the phpMyAdmin

    1. Open the XAMP app and click on the Admin button as shown in the following image

    Now you will see the phpMyAdmin page in the browser like the following.

    1. Click on the database to create a database.

    2. Enter Database name and click on the Create button

    Connect your Laravel project with the newly created Database

    1. Open the VSCode
    2. Open the .env file
    3. Fill the database connection details (the following db credentials are only for the sample purpose please use you own credentials) and save file

    Database Connection Configurations

    
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=employeecrud
    DB_USERNAME=root
    DB_PASSWORD=**********

    Create a Migration

    To create the migration , open the command prompt and enter the  following artisan command and press enter

    php artisan make:migration CreateEmployeeTable 
    or
    php artisan make:migration create_employee_table --create=employees
    

    Tips : You can create a model and migration using the following commands

    php artisan make:model CreateEmployeeTable -m

    Modify Migration file

    Open the newly created migration file (2021_11_07_064027_create_employee_table.php) and enter the following code in the up function and save file

    public function up()
        {
            Schema::table('employees', function (Blueprint $table) {
                $table->id();
                $table->string('employee_name');
                $table->string('employee_email')->unique();
                $table->text('employee_address')->nullable();
                $table->timestamps();
            });
        }
     
    

    Run the Migration

    Now Type the following command to run the migration

    php artisan migrate

    Database View After Migration

    After successful migration your database tables will look like as following

    Employee Table View

    Create Model and Controller

    Create Model

    To create model type the following command in command prompt

    php artisan make:model Employee

    Create Controller

    To create controller type  the following command and press enter

    php artisan make:controller EmployeeController --resource

    Create a Model and Controller Using a Single Command

    You can create a model and controller using a single command. Use the following command

    php artisan make:controller EmployeeController --model=Employee
    
    or
    php artisan make:controller EmployeeController --resource --model=Employee

    Enter Y and hit enter to create a model

    Controller and model created successfully

    Note: Laravel will create basic empty functions in the controller to perform CRUD operation

    Add Route and use EmployeeController in web.php

    Open the web.php file (refer the following image) and enter the following code.

    use App\Http\Controllers\EmployeeController;
    Route::resource('employees', EmployeeController::class);
    

    Code to Perform CRUD Operations

    1. Add the following code in EmployeeController.php file

    <?php
     
    namespace App\Http\Controllers;
     
    use App\Models\Employee;
    use Illuminate\Http\Request;
     
    class EmployeeController extends Controller
    {
        public function index()
        {
            $employeeData = Employee::latest()->paginate(10);
     
            return view('employees.index',compact('employeeData'))
                ->with('num1', (request()->input('page', 1) - 1) * 10);
        }
     
     
        public function create()
        {
            return view('employees.create');
        }
     
        public function store(Request $request)
        {
            $request->validate([
                'employee_email' => 'required',
            ]);
     
            Employee::create($request->all());
     
            return redirect()->route('employees.index')
                            ->with('success','Employee created successfully.');
     
        }
     
        public function show(Employee $employee)
        {
            return view('employees.show',compact('employee'));
        }
     
     
        public function edit(Employee $employee)
        {
            return view('employees.edit',compact('employee'));
        }
     
     
        public function update(Request $request, Employee $employee)
        {
            $request->validate([
                'employee_email' => 'required',
            ]);
     
            $employee->update($request->all());
     
            return redirect()->route('employees.index')
                            ->with('success','Employee updated successfully');
     
        }
     
        public function destroy(Employee $employee)
        {
            $employee->delete();
     
            return redirect()->route('employees.index')
                            ->with('success','Employee deleted successfully');
     
        }
    }
     

    2. Add the following code in Employee.php model file

    <?php
     
    namespace App\Models;
     
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
     
    class Employee extends Model
    {
        use HasFactory;
        protected $fillable = [
            'employee_name', 'employee_email','employee_address'
        ];
    }

    Add View Files

    Now we will create front end design and will create all required blade files.

    Create one Employees Folder

     First create one employees folder under view folder(resources/views) as shown in the following image

    Create blade files

    Create the following blade files under the employees folder

    1. Layout.blade.php
    2. index.blade.php
    3. create.blade.php
    4. edit.blade.php
    5. show.blade.php

    1. Layout.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>Laravel 8 CRUD Operations</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
        <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/js/all.min.js" integrity="sha512-cyAbuGborsD25bhT/uz++wPqrh5cqPh1ULJz4NSpN9ktWcA6Hnh9g+CWKeNx2R0fgQt+ybRXdabSBgYXkQTTmA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
     
    </head>
     
    <body>
        <nav class="navbar navbar-expand-lg navbar-light bg-light shadow">
            <div class="container-fluid">
              <a class="navbar-brand" href="#">suriyal.com</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">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                  <li class="nav-item">
                    <a class="nav-link active" aria-current="page" href="{{ route('employees.index') }}">Home</a>
                  </li>
     
                  <li class="nav-item dropdown">
                    <a class="nav-link active dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                      Employee
                    </a>
                    <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                      <li><a class="dropdown-item" href="{{ route('employees.create') }}">Add Employee Details</a></li>
                    </ul>
                  </li>
                </ul>
     
              </div>
            </div>
          </nav>
     
     
    <div class="container">
        @yield('content')
    </div>
     
    </body>
    </html>
    

    2 . Index.blade.php

    @extends('employees.layout')
    
    @section('content')
    
        <div class="container shadow bg-light mt-3 p-3 " >
            <div class="row">
                <div class="row margin-tb">
                    <div class="col-sm-9">
                        <h3>Laravel 8 CRUD (create, read, update and delete) Operations</h3>
                    </div>
                    <div class="col-sm-3">
                        <a class="btn btn-primary" href="{{ route('employees.create') }}"> Add Employee Details</a>
                    </div>
                </div>
            </div>
            </div>
    
        @if ($message = Session::get('success'))
            <div class="alert alert-primary card shadow">
                <p>{{ $message }}</p>
            </div>
        @endif
    
        <table class="table table-bordered table-hover">
            <tr>
                <th>#</th>
                <th>Employee Name</th>
                <th>Employee Email</th>
                <th>Employee Address</th>
                <th width="230px">Actions</th>
            </tr>
            @foreach ($employeeData as $empdata => $value)
            <tr>
                <td>{{ ++$num1 }}</td>
                <td>{{ $value->employee_name }}</td>
                <td>{{ $value->employee_email }}</td>
                <td>{{ $value->employee_address }}</td>
                <td class="shadow">
                    <form action="{{ route('employees.destroy',$value->id) }}" method="POST">
    
                        <a class="btn btn-success btn-sm" href="{{ route('employees.show',$value->id) }}"><i class="fa-solid fa-eye"></i>View</a>
                        <a class="btn btn-primary btn-sm" href="{{ route('employees.edit',$value->id) }}"><i class="fa-solid fa-pen-to-square"></i>Edit</a>
    
                        @csrf
                        @method('DELETE')
                        <button type="submit" class="btn btn-danger btn-sm"><i class="fa-solid fa-trash-can"></i>Delete</button>
    
                    </form>
                </td>
            </tr>
            @endforeach
        </table>
    
    
        {!! $employeeData->links() !!}
    @endsection
    

      3. Create.blade.php

    @extends('employees.layout')
     
    @section('content')
     
    <div class="container shadow-none bg-light mt-3  " style="width: 50rem;">
    <div class="row card p-5 text-center">
        <div class="row margin-tb">
            <div class="col-sm-11">
                <h2>Add Employee Details</h2>
            </div>
            <div class="col-sm-1">
                <a class="btn btn-primary" href="{{ route('employees.index') }}"><i class="fa-solid fa-house"></i></a>
            </div>
        </div>
    </div>
    </div>
     
    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Errors!</strong>Please chek carefully....<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
     
    <form action="{{ route('employees.store') }}" method="POST">
        @csrf
        <form>
     
    <div class="container card shadow-lg p-3 mb-5" style="width: 50rem;">
            <div class="row mb-12 p-3">
              <label for="employee_name" class="col-sm-3 col-form-label">Employee Name</label>
              <div class="col-sm-9">
                <input type="text" class="form-control" name="employee_name" id="employee_name" placeholder="Enter Employee Name">
              </div>
            </div>
     
            <div class="row mb-12 p-3">
                <label for="employee_email" class="col-sm-3 col-form-label">Employee Email</label>
                <div class="col-sm-9">
                  <input type="email" class="form-control" name="employee_email" id="employee_email" placeholder="Enter Employee Email Id">
                </div>
              </div>
     
              <div class="row mb-12 p-3">
                <label for="employee_address" class="col-sm-3 col-form-label">Employee Address</label>
                <div class="col-sm-9">
                  <input type="text" class="form-control" name="employee_address" id="employee_address" placeholder="Enter Employee Address">
                </div>
              </div>
     
     
              <div class="row card text-center">
     
              <div class="col-sm-12 p-3">
                <button type="submit" class="btn btn-primary btn-lg shadow-lg">Save</button>
                <a class="btn btn-danger btn-lg shadow-lg" href="{{ route('employees.index') }}"> Cancel</a>
              </div>
     
            </div>
     
        </div>
     
    </form>
     
    @endsection
    

      4. Edit.blade.php

    @extends('employees.layout')
     
    @section('content')
     
        <div class="container shadow-none bg-light mt-5  " style="width: 50rem;">
            <div class="row card p-5 text-center">
                <div class="row margin-tb">
                    <div class="col-sm-11">
                        <h2>Edit Employee Details</h2>
                    </div>
                    <div class="col-sm-1">
                        <a class="btn btn-primary" href="{{ route('employees.index') }}"> <i class="fa-solid fa-backward"></i></a>
                    </div>
                </div>
            </div>
            </div>
     
        @if ($errors->any())
        <div class="alert alert-warning">
            <strong>Errors!</strong>Please chek carefully....<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
     
     <form action="{{ route('employees.update',$employee->id) }}" method="POST">
            @csrf
            @method('PUT')
     
       <div class="container card shadow-lg p-3 mb-5" style="width: 50rem;">
        <div class="row mb-12 p-3">
          <label for="employee_name" class="col-sm-3 col-form-label">Employee Name</label>
          <div class="col-sm-9">
            <input type="text" class="form-control" value="{{ $employee->employee_name }}" name="employee_name" id="employee_name" placeholder="Enter Employee Name">
          </div>
        </div>
     
        <div class="row mb-12 p-3">
            <label for="employee_email" class="col-sm-3 col-form-label">Employee Email</label>
            <div class="col-sm-9">
              <input type="email" class="form-control" value="{{ $employee->employee_email }}" name="employee_email" id="employee_email" placeholder="Enter Employee Email Id">
            </div>
          </div>
     
          <div class="row mb-12 p-3">
            <label for="employee_address" class="col-sm-3 col-form-label">Employee Address</label>
            <div class="col-sm-9">
              <input type="text" class="form-control" value="{{ $employee->employee_address }}" name="employee_address" id="employee_address" placeholder="Enter Employee Address">
            </div>
          </div>
     
     
          <div class="row card text-center">
     
          <div class="col-sm-12 p-3">
            <button type="submit" class="btn btn-primary btn-lg shadow-lg">Update</button>
            <a class="btn btn-danger btn-lg shadow-lg" href="{{ route('employees.index') }}"> Cancel</a>
          </div>
     
        </div>
     
    </div>
    </form>
     
    @endsection
    

      5. show.blade.php

    @extends('employees.layout')
     
    @section('content')
     
        <div class="container shadow-none bg-light mt-5  " style="width: 50rem;">
            <div class="row card p-5 text-center">
                <div class="row margin-tb">
                    <div class="col-sm-11">
                        <h2>Displaying Employee Details</h2>
                    </div>
                    <div class="col-sm-1">
                        <a class="btn btn-primary" href="{{ route('employees.index') }}"> <i class="fa-solid fa-backward"></i></a>
                    </div>
                </div>
            </div>
            </div>
     
    <div class="container card shadow-lg p-3 mb-5" style="width: 50rem;">
        <div class="row mb-12 p-3">
          <label for="employee_name" class="col-sm-3 col-form-label">Employee Name</label>
          <div class="col-sm-9">
            <input type="text" class="form-control" value="{{ $employee->employee_name }}"  name="employee_name" id="employee_name" placeholder="Enter Employee Name" disabled readonly>
          </div>
        </div>
     
        <div class="row mb-12 p-3">
            <label for="employee_email" class="col-sm-3 col-form-label">Employee Email</label>
            <div class="col-sm-9">
              <input type="email" class="form-control" value="{{ $employee->employee_email }}" name="employee_email" id="employee_email" placeholder="Enter Employee Email Id" disabled readonly>
            </div>
          </div>
     
          <div class="row mb-12 p-3">
            <label for="employee_address" class="col-sm-3 col-form-label">Employee Address</label>
            <div class="col-sm-9">
              <input type="text" class="form-control" value="{{ $employee->employee_address }}"  name="employee_address" id="employee_address" placeholder="Enter Employee Address" disabled readonly>
            </div>
          </div>
     
    </div>
     
    @endsection
    

    Run the application using the following artisan command

    php artisan serve

    Open the browser and type the following url

    http://localhost:8000/employees

    Thank you for reading this Laravel CRUD tutorial

    Have a great learning experience !

    2 responses to “Laravel 8 CRUD Operations Tutorial”

    Leave a Reply

    Your email address will not be published. Required fields are marked *