Laravel 10 Yajra DataTables CRUD Tutorial

Laravel 10 Yajra DataTables CRUD Tutorial

If you are looking to create a CRUD (Create, Read, Update, Delete) application in Laravel using DataTables.js, then this tutorial is tailored for you. In this comprehensive guide, you will learn how to leverage the power of Yajra DataTables.js package to build a robust CRUD application in Laravel.

Laravel 10 CRUD Yajra DataTables Tutorial

By using the following steps, you can create simple crud applications using yajra DataTables in laravel 10 apps:

  • Step 1 – Setup New Laravel 10 App
  • Step 2 – Setup Database with Laravel App
  • Step 3 – Install and Configure Yajra Datatables
  • Step 4 – Create Model & Migration
  • Step 5 – Add Routes
  • Step 6 – Generate CRUD Controller By Artisan Command
  • Step 7 – Create Blade Views File
    • Make Directory Name Companies
    • index.blade.php
    • create.blade.php
    • edit.blade.php
    • action.blade.php
  • Step 8 – Run Development Server

Step 1 – Setup New Laravel 10 App

First of all, start your terminal to download or install Laravel 10 new setup. Execute the following command into it to install new Laravel 10 app into your system:

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

Step 2 – Setup Database with Laravel App

Configure the database with your apps. So, visit your app root directory and find .env file. Then configure database details as follows:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password

Step 3 – Install and Configure Yajra Datatables

Navigate to your downloaded Laravel 10 app directory. And then install Yajra Datatables Packages in your Laravel 10 by using the following command:

composer require yajra/laravel-datatables-oracle

Then configure datatables package. So go to the config directory and open app.php file. And add the following service providers into app.php file:

config/app.php

 'providers' => [
   
   Yajra\Datatables\DatatablesServiceProvider::class,
],

 'aliases' => [

  'Datatables' => Yajra\Datatables\Facades\Datatables::class,
] 

Then publish laravel datatables vendor package by using the following command:

php artisan vendor:publish

Step 4 – Create Model & Migration

Open again your command prompt. And run the following command on it. To create model and migration file:

php artisan make:model Company -m

After that, open create_companies_table.php file inside /database/migrations/ directory. And the update the function up() with following code:

    public function up()
    {
        Schema::create('companies', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('address');
            $table->timestamps();
        });
    }

Then, open again command prompt and run the following command to create tables into database:

php artisan migrate

Step 5 – Add Routes

In this step, create routes for laravel crud app. So, open web.php file from the routes directory of laravel CRUD app. And update the following routes into the web.php file:

Route::resource('companies', CompanyCRUDController::class);
Route::post('delete-company', [CompanyCRUDController::class,'destroy']);

Step 6 – Generate CRUD Controller By Artisan Command

Create a controller by using the following command on the command prompt to create a controller file:

php artisan make:controller CompanyCRUDController

After that, visit app/Http/controllers and open CompanyCRUDController.php file. And update the following code into it:

<?php
  
namespace App\Http\Controllers;
   
use App\Models\Company;
use Illuminate\Http\Request;
use Datatables;
  
class CompanyCRUDController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        if(request()->ajax()) {
            return datatables()->of(Company::select('*'))
            ->addColumn('action', 'companies.action')
            ->rawColumns(['action'])
            ->addIndexColumn()
            ->make(true);
        }
        return view('companies.index');

    }
     
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('companies.create');
    }
    
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required',
            'address' => 'required'
        ]);

        $company = new Company;

        $company->name = $request->name;
        $company->email = $request->email;
        $company->address = $request->address;


        $company->save();

     
        return redirect()->route('companies.index')
                        ->with('success','Company has been created successfully.');
    }
     
    /**
     * Display the specified resource.
     *
     * @param  \App\company  $company
     * @return \Illuminate\Http\Response
     */
    public function show(Company $company)
    {
        return view('companies.show',compact('company'));
    } 
     
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Company  $company
     * @return \Illuminate\Http\Response
     */
    public function edit(Company $company)
    {
        return view('companies.edit',compact('company'));
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\company  $company
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required',
            'address' => 'required'
        ]);
        
        $company = Company::find($id);

        $company->name = $request->name;
        $company->email = $request->email;
        $company->address = $request->address;

        $company->save();
    
        return redirect()->route('companies.index')
                        ->with('success','Company Has Been updated successfully');
    }
    
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Company  $company
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
    
        $com = Company::where('id',$request->id)->delete();
     
        return Response()->json($com);
    }
}

Step 6 – Create Blade Views File

Create the directory and some blade view, see the following:

  • Make Directory Name Companies
  • index.blade.php
  • create.blade.php
  • edit.blade.php
  • action.blade.php

Create directory name companies inside resources/views directory.

Note that, create index.blade.php, create.blade.php and edit.blade inside companies directory. And update the following code into following files:

index.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel 10 DataTables CRUD Tutorial From Scratch - Tutsmake.com</title>
    
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >


  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

  <link  href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">

  <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>

</head>
<body>

<div class="container mt-2">

<div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 10 CRUD using DataTables Tutorial</h2>
            </div>
            <div class="pull-right mb-2">
                <a class="btn btn-success" href="{{ route('companies.create') }}"> Create Company</a>
            </div>
        </div>
    </div>
   
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif

    <div class="card-body">

        <table class="table table-bordered" id="datatable-crud">
           <thead>
              <tr>
                 <th>Id</th>
                 <th>Name</th>
                 <th>Email</th>
                 <th>Address</th>
                 <th>Created at</th>
                 <th>Action</th>
              </tr>
           </thead>
        </table>

    </div>
   
</div>
</body>
<script type="text/javascript">
     
 $(document).ready( function () {
  $.ajaxSetup({
    headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  });
    $('#datatable-crud').DataTable({
           processing: true,
           serverSide: true,
           ajax: "{{ url('companies') }}",
           columns: [
                    { data: 'id', name: 'id' },
                    { data: 'name', name: 'name' },
                    { data: 'email', name: 'email' },
                    { data: 'address', name: 'address' },
                    { data: 'created_at', name: 'created_at' },
                    {data: 'action', name: 'action', orderable: false},
                 ],
                 order: [[0, 'desc']]
       });

    $('body').on('click', '.delete', function () {

       if (confirm("Delete Record?") == true) {
        var id = $(this).data('id');
         
        // ajax
        $.ajax({
            type:"POST",
            url: "{{ url('delete-company') }}",
            data: { id: id},
            dataType: 'json',
            success: function(res){

              var oTable = $('#datatable-crud').dataTable();
              oTable.fnDraw(false);
           }
        });
       }

     });
  });

</script>
</html>

create.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Company Form - Laravel 10 Datatable CRUD</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
</head>
<body>

<div class="container mt-2">
  
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left mb-2">
            <h2>Add Company</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="{{ route('companies.index') }}"> Back</a>
        </div>
    </div>
</div>
   
  @if(session('status'))
    <div class="alert alert-success mb-1 mt-1">
        {{ session('status') }}
    </div>
  @endif
   
<form action="{{ route('companies.store') }}" method="POST" enctype="multipart/form-data">
    @csrf
  
     <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Company Name:</strong>
                <input type="text" name="name" class="form-control" placeholder="Company Name">
               @error('name')
                  <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
               @enderror
            </div>
        </div>

        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Company Email:</strong>
                 <input type="email" name="email" class="form-control" placeholder="Company Email">
                @error('email')
                  <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
               @enderror
            </div>
        </div>

        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Company Address:</strong>
                 <input type="text" name="address" class="form-control" placeholder="Company Address">
                @error('address')
                  <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
               @enderror
            </div>
        </div>
        <button type="submit" class="btn btn-primary ml-3">Submit</button>
    </div>
   
</form>

</body>
</html>

edit.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Company Form - Laravel 10 Datatable CRUD Tutorial</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
</head>
<body>

<div class="container mt-2">

    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Edit Company</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('companies.index') }}" enctype="multipart/form-data"> Back</a>
            </div>
        </div>
    </div>
   
  @if(session('status'))
    <div class="alert alert-success mb-1 mt-1">
        {{ session('status') }}
    </div>
  @endif
  
    <form action="{{ route('companies.update',$company->id) }}" method="POST" enctype="multipart/form-data">
        @csrf
        @method('PUT')
   
         <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Company Name:</strong>
                    <input type="text" name="name" value="{{ $company->name }}" class="form-control" placeholder="Company name">
                    @error('name')
                     <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                    @enderror
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Company Email:</strong>
                     <input type="email" name="email" class="form-control" placeholder="Company Email" value="{{ $company->email }}">
                    @error('email')
                      <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                   @enderror
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Company Address:</strong>
                    <input type="text" name="address" value="{{ $company->address }}" class="form-control" placeholder="Company Address">
                    @error('address')
                     <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                    @enderror
                </div>
            </div>
              <button type="submit" class="btn btn-primary ml-3">Submit</button>
          
        </div>
   
    </form>
</div>

</body>
</html>

action.blade.php

<a href="{{ route('companies.edit',$id) }}" data-toggle="tooltip" data-original-title="Edit" class="edit btn btn-success edit">
	Edit
</a>
<a href="javascript:void(0)" data-id="{{ $id }}" data-toggle="tooltip" data-original-title="Delete" class="delete btn btn-danger">
	Delete
</a>

Note that, the following jQuery ajax code will delete data from datatable and database without refresh or reload page in Laravel 10 app:

    $('body').on('click', '.delete', function () {

       if (confirm("Delete Record?") == true) {
        var id = $(this).data('id');
         
        // ajax
        $.ajax({
            type:"POST",
            url: "{{ url('delete-company') }}",
            data: { id: id},
            dataType: 'json',
            success: function(res){

              var oTable = $('#datatable-crud').dataTable();
              oTable.fnDraw(false);
           }
        });
       }

     });

If you submit the add or edit form blank. So the error message will be displayed with the help of the code given below:

  @error('name')
  <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
  @enderror

Don’t forget to add the following yajra datatables jquery library into index.blade.php file:

  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

  <link  href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">

  <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>

Step 8 – Run Development Server

Last step, open command prompt and run the following command to start developement server:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/companies

Recommended Laravel 10 Posts

Recommended:- Laravel Try Catch

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

One reply to Laravel 10 Yajra DataTables CRUD Tutorial

  1. Really an awesome tutorial. Works for Laravel 10.

    Thanks alot

Leave a Reply

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