In this tutorial you will learn about the Laravel 9 Yajra DataTables CRUD Example Tutorial and its application with practical example.
In this Laravel 9 Yajra DataTables CRUD Example Tutorial I’ll show you how to create a simple crud application using yajra Datatables in laravel 9. In this example we will learn how to create a simple crud operation application using Datatables in laravel 9. In this laravel 9 crud application we will be using jQuery and ajax to delete data from datatable crud app and MySQL database in laravel 9.
Laravel 9 Ajax CRUD Using Datatable Tutorial
In this example we will implement ajax based CRUD (Create, Read, Update and Delete) operations using datatable js. In this tutorial, we will be using yajra datatable package for listing of records with pagination, sorting and filter (search) feature.
Laravel 9 Yajra DataTables CRUD Example Tutorial
In this step by step guide, we will be creating a simple laravel 9 application to demonstrate you how to install yajra datatable package and implement ajax based CRUD operations with datatable js.
- Download Laravel 9 App
- Database Configuration
- Installing Yajra Datatables
- Build Model & Migration
- Create Routes
- Generate CRUD Controller By Artisan Command
- Create Blade Views File
- Run Development Server
Install Laravel 9
First of all we need to create a fresh laravel project, download and install Laravel 9 using the below command
1 |
composer create-project --prefer-dist laravel/laravel larablog |
Configure Database In .env file
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
.env
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=larablog DB_USERNAME=root DB_PASSWORD= |
Install Yajra Datatable Package
In this step, we will install Yajra Datatables Package via the composer dependency manager. Use the following command to install Yajra Datatables Package.
1 |
composer require yajra/laravel-datatables-oracle |
After Installing Yajra Datatables package, we need to add service provider and alias in config/app.php file as following.
config/app.php
1 2 3 4 5 6 7 8 9 |
'providers' => [ // Other service providers… Yajra\DataTables\DataTablesServiceProvider::class, ], 'aliases' => [ // Other aliases… 'Datatables' => Yajra\Datatables\Facades\Datatables::class, ], |
Now, we need to publish laravel datatables vendor package by using the following command:
1 |
php artisan vendor:publish |
Build Model & Migration
Now, in this step we will create model and migration file for form. Please run the following command:
1 |
php artisan make:model Company -m |
Once above command is executed there will be a migration file created inside database/migrations/ directory, just open create_companies_table.php migration file and update the function up() method as following:
1 2 3 4 5 6 7 8 9 10 |
public function up() { Schema::create('companies', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email'); $table->string('address'); $table->timestamps(); }); } |
Now, run the migration to create database table using following artisan command:
1 |
php artisan migrate |
Create Routes
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 |
Route::resource('companies', CompanyCRUDController::class); Route::post('delete-company', [CompanyCRUDController::class,'destroy']); |
Generate CRUD Controller By Artisan Command
Next, we have to create a controller to for laravel crud operations. Lets Create a controller named CompanyCRUDController using command given below –
1 |
php artisan make:controller CompanyCRUDController |
Open the CompanyCRUDController.php file and put the following code in it.
app/Http/Controllers/CompanyCRUDController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
<?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); } } |
Create Blade Views File
Create the directory and create blade view file for CRUD operations as 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.
index.blade.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Laravel 9 DataTables CRUD Tutorial</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 9 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Add Company Form - Laravel 9 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Edit Company Form - Laravel 9 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
1 2 3 4 5 6 |
<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> |
In the above code following jQuery ajax code is used to delete from datatable and database without refresh or reload page in laravel 9:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$('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); } }); } }); |
Start Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://localhost:8000/companies |