laravel 6 First Ajax CRUD Application – Ajax CRUD will make user experience better. We would love to share with you how to create ajax CRUD operation in laravel based project.Today we will implement ajax CRUD application in new laravel 6 without page refresh or reload.
We will use boostrap modal and jquery ajax for create laravel application crud operation without page reload or refresh. In this example we will show users list (user management) with pagination and also provide a demo application for your testing. In the last of example we will attatched a live demo button. click on live demo button and test demo laravel 6 crud application in your hand
Contents
- Laravel Setup
- Database Connection
- Create Model and Migration
- Create Route
- Generate(create) Controller
- Create Blade View
- Start Development Server
- Conclusion
First Install New Laravel Setup
In this step, we will download a new laravel 6 setup. Use the below following command and download it :
composer create-project --prefer-dist laravel/laravel LaravelAjax
Database Connection
Next Go to your project root directory, find .env file and setup database credential here :
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, We will create table using laravel migration. If you don’t want to use laravel migration you can skip this step. Run the below command to create migration
php artisan make:migration create_users_table
Next go to app/datatabase/migrations and open users migration file and put the below code here :
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->string('email')->nullable();
$table->timestamps();
});
}
Before we run php artisan migrate command go to app/providers/AppServiceProvider.php and put the below code :
...
use Illuminate\Support\Facades\Schema;
....
function boot()
{
Schema::defaultStringLength(191);
}
...
Next migrate the table using the below command :
php artisan migrate
Create Route
Create one resource route. It contain by default multiple method like create,store,update,edit and destory :
//Ajax Crud Laravel
Route::resource('ajax-crud', 'AjaxController');
Generate (Create) Controller
Now we will create resource controller. Use the below command for generate controller
php artisan make:controller AjaxController --resource
Next we will use only four methods the from resource controller. Next open your controller and replace the methods given in below :
<?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) { $user = User::updateOrCreate( ['id' => $request->user_id], ['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); } }
Create blade view :
In this step, we will create one blade file name ajax-crud.blade.php.
In this ajax-crud file we will implement users list, one boostrap modal for create and edit of users detail :
<!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 - W3path.com</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 - <a href="https://www.w3path.com" target="_blank" >W3path</a></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.w3path.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 colspan="2"> <a href="javascript:void(0)" id="edit-user" data-id="{{ $u_info->id }}" class="btn btn-info mr-2">Edit</a> <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 :
<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> <form id="userForm" name="userForm" class="form-horizontal"> <div class="modal-body"> <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> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary" id="btn-save" value="create"> Save changes </button> </div> </form> </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 :
<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"); if(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.w3path.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 colspan="2"><a href="javascript:void(0)" id="edit-user" data-id="' + data.id + '" class="btn btn-info mr-2">Edit</a>'; user += '<a href="javascript:void(0)" id="delete-user" data-id="' + data.id + '" class="btn btn-danger delete-user ml-1">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>
Start Development Server
In this step, we will use the php artisan serve command . It will start your server locally
php artisan serve
If you want to run the project diffrent port so use this below command
php artisan serve --port=8080
Now we are ready to run our example so run bellow command to quick run.
http://127.0.0.1:8000/ajax-crud
Conclusion
In this laravel ajax crud operation, we have successfully created ajax crud application in laravel 6 application.
Recommended Posts
If you have any questions or thoughts to share, use the comment form below to reach us.
Woah! I’m really enjoying the template/theme of this blog. It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between superb usability and visual appearance. I must say that you’ve done a great job with this. In addition, the blog loads super quick for me on Opera. Exceptional Blog!
There is bug in demo code when i have click on delete button at a time system give me alert to delete the data but when i click on ” cancel” button data is deleted successfully
sol please add ” return false; ” after alert();
Hi Devang,
Thanks to pointing me there, I have made the changes
Thanks
Edit Function is not working… when edit performed, it does not modifies the previous record but actually creates a new one.
hi, thanks… but, how to display data in the dropdown to be changed
How to display Custom Validation Message while adding User?
Thank you so much.
Why edit and create is not working??
We’re a gaggle of volunteers and starting a new scheme in our community.
Your website offered us with useful information to work on. You have done an impressive activity and our entire
community will be thankful to you.
Stop by my web page :: cheap flights
Wow, incredible blog layout! How long have you been blogging for?
you make blogging look easy. The overall look of your site is wonderful,
let alone the content!
Look into my web-site; cheap flights
Good day! I know this is kinda off topic nevertheless
I’d figured I’d ask. Would you be interested in trading links or maybe
guest authoring a blog post or vice-versa? My site goes over a
lot of the same subjects as yours and I believe
we could greatly benefit from each other. If you might be interested feel free to send me an e-mail.
I look forward to hearing from you! Great blog by the way!
my web site: cheap flights
I was suggested this website by my cousin.
I am not sure whether this post is written by him as no one else know such detailed about my problem.
You are amazing! Thanks!
Feel free to visit my webpage :: cheap flights (http://tinyurl.com/y2g6co44)
Your style is very unique in comparison to other people I’ve read stuff from.
I appreciate you for posting when you’ve got the opportunity,
Guess I will just book mark this web site.
Also visit my web page; cheap flights
Woah! I’m really digging the template/theme of this website.
It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between superb
usability and visual appearance. I must say you have done a great
job with this. Also, the blog loads very quick for me on Firefox.
Exceptional Blog!
Look at my site – cheap flights (tinyurl.com)
online pharmacy without prescription top rated canadian pharmacies online mental illness
canada pharmacies online top rated canadian pharmacies online aarp recommended canadian pharmacies
discount drugs online pharmacy canadian drug stores online canada online pharmacies
cialis free shipping canadian mastercard cialis free cialis online
viagra usa viagra coupons meds online
paypal payment for viagra online prescription drugs 100 mg viagra
online canadian pharmacy pharmeasy drugs without prescription
pills viagra pharmacy 100mg viagra online no prescription pills viagra pharmacy 100mg
viagra gel australia cheap viagra no prescription what\’s the least expensive place to buy viagra
discount drugs online pharmacy canada prescriptions drugs erectile dysfunction medications
cialis bad for health cialis packungsgroesse pareri sul cialis
You made some good points there. I looked on the net for
additional information about the issue and found most people will go along with your views on this web site.
my blog post: cheap flights [tinyurl.com]
online cash loan in india payday loans in o’fallon mo no credit check payday loans in hammond la
instant payday loans hawaii online payday loans winnipeg cash loans lake elsinore
buying viagra in las vegas viagra in the usa overnight delivery viagra in mexico over the counter
cialis vs viagra vs levitra cost quem toma remedio para pressГЈo pode tomar cialis cialis 20 mg ou 5 mg
online purchase viagra sildenafil 100 canada viagra for female online india
z cash payday loans houston tx payday loans manitoba law best payday loans in amarillo tx
Phd In Education Jobs College Of Education Quilt
Feel free to visit my website; pdf book
fast cash loans in sa cash advance in nederland texas quick cash loan illinois
Very smooth text.
free robux
no prescription needed viagra australia reasons to use viagra cheap viagra
mаgnificent submit, veгy informative. I wonder why the other specialists of this sector do not understand this.
You must cⲟntinuе your writing. I am sure, you’ve a great readers’
base already!
Review my blog post isabella