In this tutorial you will learn about the Laravel 7/6 Ajax CRUD Example and its application with practical example.
In this Laravel 7/6 Ajax CRUD operation example tutorial I’ll show you how to create a simple ajax crud application in laravel 7/6. In this example we will learn how to create a simple ajax crud operation application in laravel 7/6. In this laravel 7/6 ajax crud application we will be using jQuery and ajax to delete data from datatable crud app and MySQL database in laravel 7/6 app.
In this tutorial, you will learn to implement ajax based CRUD (Create, Read, Update and Delete) operations in laravel.
Laravel 7/6 DataTable Ajax CRUD Example Tutorial
In this step by step guide, we will be creating a simple laravel 7/6 application to demonstrate you how to implement ajax based CRUD operations in laravel.
Laravel 7/6 Ajax CRUD Example
- First Install New Laravel Setup
- Configure .env file
- Create One Model and Migration
- Make Route
- Generate(create) Controller
- Create Blade View
- Start Development Server
- Conclusion
1). First Install New Laravel Setup
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
2). Configure .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.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here |
Next go to app/datatabase/migrations and open users migration file and put the below code here
1 2 3 4 5 6 7 8 9 |
public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name')->nullable(); $table->string('email')->nullable(); $table->timestamps(); }); } |
Now, go to app/providers/AppServiceProvider.php and put the below code :
1 2 3 4 5 6 7 8 9 |
... use Illuminate\Support\Facades\Schema; .... function boot() { Schema::defaultStringLength(191); } ... |
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan migrate |
3). Make Route
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 |
Route::resource('ajax-crud', 'AjaxController'); |
4). Generate (Create) Controller
In this step we will create a resource controller named AjaxController for crud operations using following command:
1 |
php artisan make:controller AjaxController --resource |
Next open your controller and replace crud methods as following:
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 |
<?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use Redirect,Response; class AjaxController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $data['users'] = User::orderBy('id','desc')->paginate(8); return view('ajax-crud',$data); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $userId = $request->user_id; $user = User::updateOrCreate(['id' => $userId], ['name' => $request->name, 'email' => $request->email]); return Response::json($user); } /** * Show the form for editing the specified resource. * * @param \App\Product $product * @return \Illuminate\Http\Response */ public function edit($id) { $where = array('id' => $id); $user = User::where($where)->first(); return Response::json($user); } /** * Remove the specified resource from storage. * * @param \App\Product $product * @return \Illuminate\Http\Response */ public function destroy($id) { $user = User::where('id',$id)->delete(); return Response::json($user); } } |
5). Create blade view :
In this step, we will create one blade file name ajax-crud.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 |
<!DOCTYPE html> <html> <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"> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>laravel 6 First Ajax CRUD Application</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" /> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <style> .container{ padding: 0.5%; } </style> </head> <body> <div class="container"> <h2 style="margin-top: 12px;" class="alert alert-success">laravel 6 First Ajax CRUD Application</h2><br> <div class="row"> <div class="col-12"> <a href="javascript:void(0)" class="btn btn-success mb-2" id="create-new-user">Add User</a> <a href="https://www.w3adda.com/jquery-submit-form-ajax-php-laravel-5-7-without-page-load/" class="btn btn-secondary mb-2 float-right">Back to Post</a> <table class="table table-bordered" id="laravel_crud"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Email</th> <td colspan="2">Action</td> </tr> </thead> <tbody id="users-crud"> @foreach($users as $u_info) <tr id="user_id_{{ $u_info->id }}"> <td>{{ $u_info->id }}</td> <td>{{ $u_info->name }}</td> <td>{{ $u_info->email }}</td> <td><a href="javascript:void(0)" id="edit-user" data-id="{{ $u_info->id }}" class="btn btn-info">Edit</a></td> <td> <a href="javascript:void(0)" id="delete-user" data-id="{{ $u_info->id }}" class="btn btn-danger delete-user">Delete</a></td> </tr> @endforeach </tbody> </table> {{ $users->links() }} </div> </div> </div> </body> </html> |
Next step, we will create one modal. After create a modal it put closing of last div tag :
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 |
<div class="modal fade" id="ajax-crud-modal" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="userCrudModal"></h4> </div> <div class="modal-body"> <form id="userForm" name="userForm" class="form-horizontal"> <input type="hidden" name="user_id" id="user_id"> <div class="form-group"> <label for="name" class="col-sm-2 control-label">Name</label> <div class="col-sm-12"> <input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required=""> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Email</label> <div class="col-sm-12"> <input type="email" class="form-control" id="email" name="email" placeholder="Enter Email" value="" required=""> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" id="btn-save" value="create">Save changes </button> </div> </div> </div> </div> |
Next we will implement the ajax crud logic inside the script. Open your ajax-crud blade view file and put the below code after closing of body tag
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 |
<script> $(document).ready(function () { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); /* When user click add user button */ $('#create-new-user').click(function () { $('#btn-save').val("create-user"); $('#userForm').trigger("reset"); $('#userCrudModal').html("Add New User"); $('#ajax-crud-modal').modal('show'); }); /* When click edit user */ $('body').on('click', '#edit-user', function () { var user_id = $(this).data('id'); $.get('ajax-crud/' + user_id +'/edit', function (data) { $('#userCrudModal').html("Edit User"); $('#btn-save').val("edit-user"); $('#ajax-crud-modal').modal('show'); $('#user_id').val(data.id); $('#name').val(data.name); $('#email').val(data.email); }) }); //delete user login $('body').on('click', '.delete-user', function () { var user_id = $(this).data("id"); confirm("Are You sure want to delete !"); $.ajax({ type: "DELETE", url: "{{ url('ajax-crud')}}"+'/'+user_id, success: function (data) { $("#user_id_" + user_id).remove(); }, error: function (data) { console.log('Error:', data); } }); }); }); if ($("#userForm").length > 0) { $("#userForm").validate({ submitHandler: function(form) { var actionType = $('#btn-save').val(); $('#btn-save').html('Sending..'); $.ajax({ data: $('#userForm').serialize(), url: "https://www.w3adda.com/laravel-example/ajax-crud/store", type: "POST", dataType: 'json', success: function (data) { var user = '<tr id="user_id_' + data.id + '"><td>' + data.id + '</td><td>' + data.name + '</td><td>' + data.email + '</td>'; user += '<td><a href="javascript:void(0)" id="edit-user" data-id="' + data.id + '" class="btn btn-info">Edit</a></td>'; user += '<td><a href="javascript:void(0)" id="delete-user" data-id="' + data.id + '" class="btn btn-danger delete-user">Delete</a></td></tr>'; if (actionType == "create-user") { $('#users-crud').prepend(user); } else { $("#user_id_" + data.id).replaceWith(user); } $('#userForm').trigger("reset"); $('#ajax-crud-modal').modal('hide'); $('#btn-save').html('Save Changes'); }, error: function (data) { console.log('Error:', data); $('#btn-save').html('Save Changes'); } }); } }) } </script> |
6). Run 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://127.0.0.1:8000/ajax-crud |