Laravel 7/6 Ajax CRUD Tutorial with Bootstrap 4 Modal and Pagination Example
In this post we will give you information about Laravel 7/6 Ajax CRUD Tutorial with Bootstrap 4 Modal and Pagination Example. Hear we will give you detail about Laravel 7/6 Ajax CRUD Tutorial with Bootstrap 4 Modal and Pagination ExampleAnd how to use it also give you demo for it if it is necessary.
In this tutorial, we’ll learn to build a CRUD example with Laravel 7/6, Bootstrap 4, jQuery, and Ajax.
We’ll see by example how to perform Ajax CRUD operations in Laravel 6/7 with a bootstrap modal, datatable and pagination.
Using Ajax with Laravel 7/6 for CRUD Operations
We’ll be using the jQuery ajax()
method for sending Ajax requests.
We’ll be using yajra
datatable for creating a datatable.
- Step 1 – Installing Laravel 7
- Step 2 – Installing Yajra Datatable
- Step 3 – Configuring a MySQL Database
- Step 4 – Creating a Laravel 7 Migration
- Step 5 – Adding a Laravel 7 Route
- Step 6 – Adding a Laravel 7 Controller and Model
- Step 7 – Adding a Blade Template View
- Step 8 – Serving the Laravel 7 Application
Step 1 – Installing Laravel 7
Let’s get started by installing Laravel 7 in our development machine.
Head to a new command-line interface and run the following command:
$ composer create-project --prefer-dist laravel/laravel ajax-crud-example
Step 2 – Installing Yajra Datatable
Next, let’s install the yajra
datatable package in our Laravel 7 project using following command:
$ composer require yajra/laravel-datatables-oracle
Next, you need to add it to the providers
and aliases
arrays:
'providers' => [ YajraDataTablesDataTablesServiceProvider::class,]'aliases' => [ 'DataTables' => YajraDataTablesFacadesDataTables::class,]
Step 3 – Configuring a MySQL Database
Next, let’s configure a MySQL database for our Laravel 7 project. Make sure you have created a database then go to the .env
file and add the information for connecting to your database:
DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=mydbDB_USERNAME= rootDB_PASSWORD= root
Step 4 – Creating a Laravel 7 Migration
Let’s now create a migration file for a customers
table. Head back to your terminal and run the following command:
$ php artisan make:migration create_customers_table --create=customers
Next, open the migration file in the database/migrations
folder update it as follows to create a customers
database table:
<?phpuseIlluminateSupportFacadesSchema;useIlluminateDatabaseSchemaBlueprint;useIlluminateDatabaseMigrationsMigration;classCreateCustomersTableextendsMigration{/*** Run the migrations.** @return void*/publicfunctionup(){Schema::create('customers',function(Blueprint$table){$table->bigIncrements('id');$table->string('firstName');$table->string('lastName');$table->text('info');$table->timestamps();});}/*** Reverse the migrations.** @return void*/publicfunctiondown(){Schema::dropIfExists('customers');}}
Next, you can create the table in the database by running the following command:
$ php artisan migrate
Step 5 – Adding a Laravel 7 Route
Let’s now create a Laravel 7 route for accessing the view.
Go to the routes/web.php
file and add following resource route:
Route::resource('customers','CustomerController');
Step 6 – Adding a Laravel 7 Controller and Model
Head back to your terminal and run the following command to generate a controller:
$ php artisan controller:make CustomerController
Next, open the app/Http/Controllers/CustomerController.php
file and update it as follows:
<?phpnamespaceAppHttpControllers;useAppCustomer;useIlluminateHttpRequest;useDataTables;classCustomerControllerextendsController{/** * Display a listing of the resource. * * @return IlluminateHttpResponse */publicfunctionindex(Request$request){if($request->ajax()){$data=Customer::latest()->get();returnDatatables::of($data)->addIndexColumn()->addColumn('action',function($row){$btn='<a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Edit" >Edit</a>';$btn=$btn.' <a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Delete" >Delete</a>';return$btn;})->rawColumns(['action'])->make(true);}returnview('CustomerAjax');}/** * Store a newly created resource in storage. * * @param IlluminateHttpRequest $request * @return IlluminateHttpResponse */publicfunctionstore(Request$request){Customer::updateOrCreate(['id'=>$request->Customer_id],['firstName'=>$request->firstName,'info'=>$request->info]);returnresponse()->json(['success'=>'Customer saved successfully!']);}/** * Show the form for editing the specified resource. * * @param AppCustomer $Customer * @return IlluminateHttpResponse */publicfunctionedit($id){$Customer=Customer::find($id);returnresponse()->json($Customer);}/** * Remove the specified resource from storage. * * @param AppCustomer $Customer * @return IlluminateHttpResponse */publicfunctiondestroy($id){Customer::find($id)->delete();returnresponse()->json(['success'=>'Customer deleted!']);}}
Generating a Laravel 7 Database Model
Next, let’s generate a Customer
database model using the following command:
$ php artisan make:model Customer
Next, open the app/Customer.php
file and update it as follows:
<?phpnamespace App;use IlluminateDatabaseEloquentModel;class Customer extends Model{ protected $fillable = [ 'firstName', 'lastName', 'info' ];}
Step 7 – Adding a Blade Template View
Next, inside the resources/views/
folder, create customer.blade.php
file and update it as follows:
<!DOCTYPE html><html><head><title>Laravel 6 Ajax CRUD Example</title><metaname="csrf-token"content=""><linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css"/><linkhref="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"rel="stylesheet"><linkhref="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css"rel="stylesheet"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script><script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script><script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script></head><body><divclass="container"><h1>Laravel 6 Ajax CRUD </h1><aclass="btn btn-success"href="javascript:void(0)"id="createNewCustomer"> Create New Customer</a><tableclass="table table-bordered data-table"><thead><tr><th>No</th><th>Name</th><th>Details</th><thwidth="280px">Action</th></tr></thead><tbody></tbody></table></div><divclass="modal fade"id="ajaxModel"aria-hidden="true"><divclass="modal-dialog"><divclass="modal-content"><divclass="modal-header"><h4class="modal-title"id="modelHeading"></h4></div><divclass="modal-body"><formid="CustomerForm"name="CustomerForm"class="form-horizontal"><inputtype="hidden"name="Customer_id"id="Customer_id"><divclass="form-group"><labelfor="name"class="col-sm-2 control-label">Name</label><divclass="col-sm-12"><inputtype="text"class="form-control"id="name"name="name"placeholder="Enter Name"value=""maxlength="50"required=""></div></div><divclass="form-group"><labelclass="col-sm-2 control-label">Details</label><divclass="col-sm-12"><preid="detail"name="detail"required=""placeholder="Enter Details"class="form-control"></pre></div></div><divclass="col-sm-offset-2 col-sm-10"><buttontype="submit"class="btn btn-primary"id="saveBtn"value="create">Save changes </button></div></form></div></div></div></div></body><script type="text/javascript">$(function(){$.ajaxSetup({headers:{'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')}});vartable=$('.data-table').DataTable({processing:true,serverSide:true,ajax:"",columns:[{data:'DT_RowIndex',name:'DT_RowIndex'},{data:'firstName',name:'firstName'},{data:'lastName',name:'lastName'},{data:'info',name:'info'},{data:'action',name:'action',orderable:false,searchable:false},]});$('#createNewCustomer').click(function(){$('#saveBtn').val("create-Customer");$('#Customer_id').val('');$('#CustomerForm').trigger("reset");$('#modelHeading').html("Create New Customer");$('#ajaxModel').modal('show');});$('body').on('click','.editCustomer',function(){varCustomer_id=$(this).data('id');$.get(""+'/'+Customer_id+'/edit',function(data){$('#modelHeading').html("Edit Customer");$('#saveBtn').val("edit-user");$('#ajaxModel').modal('show');$('#Customer_id').val(data.id);$('#name').val(data.name);$('#detail').val(data.detail);})});$('#saveBtn').click(function(e){e.preventDefault();$(this).html('Sending..');$.ajax({data:$('#CustomerForm').serialize(),url:"",type:"POST",dataType:'json',success:function(data){$('#CustomerForm').trigger("reset");$('#ajaxModel').modal('hide');table.draw();},error:function(data){console.log('Error:',data);$('#saveBtn').html('Save Changes');}});});$('body').on('click','.deleteCustomer',function(){varCustomer_id=$(this).data("id");confirm("Are You sure want to delete !");$.ajax({type:"DELETE",url:""+'/'+Customer_id,success:function(data){table.draw();},error:function(data){console.log('Error:',data);}});});});</script></html>
Step 8 – Serving the Laravel 7 Application
Head back to your terminal and run the following command:
$ php artisan serve
Next open your web browser and navigate to the http://localhost:8000/customers
file.
That’s it, we have finished our Laravel 7/6 Ajax CRUD app where we have seen how to use jQuery to send Ajax requests and implement a CRUD interface for working with a MySQL database.
Hope this code and post will helped you for implement Laravel 7/6 Ajax CRUD Tutorial with Bootstrap 4 Modal and Pagination Example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs