Insert update delete Using Laravel 5.2 Ajax CRUD laravel without refresh page
CRUD operations using jQuery and Ajax in Laravel 5.2 Example
Step 1: Install Laravel 5.2 using Xampp
composer create-project --prefer-dist laravel/laravel blog "5.2.*"
Step 2: Create a MyItem Table and Model using Laravel
php artisan make:migration create_MyItems_table
get a migration file
database/migrations
migration file to create MyItems table using Laravel
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMyItemsTable extends Migration { public function up() { Schema::create('MyItems', function (Blueprint $livetabledata) { $livetabledata->increments('id'); $livetabledata->string('name'); $livetabledata->text('comment'); $livetabledata->timestamps(); }); } public function down() { Schema::drop("MyItems"); } }
Now run simple php artisan migrate cmd to run command to create a MyItem table.
MyItem Model
Create a model for MyItem table.
namespace App; use Illuminate\Database\Eloquent\Model; class MyItem extends Model { public $fillable = ['name','comment']; }
Step3: Create View using Laravel
Now Create a all this file directory ajax file and within this same directory create a view file like as a index.blade.php
resources/views/ajax/index.blade.php
<title>Laravel Create,Read,Update and Delete statement Application using Ajax without Reloading Page</title> <div class="container"> <div class="panel panel-primary"> <div class="panel-heading">Laravel Create,Read,Update and Delete statement Application using Ajax without Reloading Page <button id="laravel-addrecord" name="laravel-addrecord" class="btn btn-default pull-right">Add New MyItem</button> </div> <div class="panel-body"> <table class="table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>comment</th> <th>Actions</th> </tr> </thead> <tbody id="MyItems-list"> @foreach ($MyItems as $MyItem) <tr>id}}"> <td>{{$MyItem->id}}</td> <td>{{$MyItem->name}}</td> <td>{{$MyItem->comment}}</td> <td> <button class="btn btn-warning btn-detail open_modal">id}}">Edit</button> <button class="btn btn-danger btn-delete delete-MyItem">id}}">Delete</button> </td> </tr> @endforeach </tbody> </table> </div> </div> <div class="modal fade" id="laravelmodel" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close"><span>Γ</span></button> <h4 class="modal-title" id="laravelmodelLabel">MyItem</h4> </div> <div class="modal-body"> <form id="laraliveForm" name="laraliveForm" class="form-horizontal"> <div class="form-group error"> <label for="inputName" class="col-sm-3 control-label">Name</label> <div class="col-sm-9"> </div> </div> <div class="form-group"> <label for="inputDetail" class="col-sm-3 control-label">comment</label> <div class="col-sm-9"> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" id="laracrud-btnsave" value="add">Save changes</button> </div> </div> </div> </div> </div>
Step4: Include JS file using Laravel Project
Now in this simple step create a file like as a ajaxscript.js file in following this dir path public/js/ajaxscript.js
public/js/ajaxscript.js
var url = "http://localhost:8080/blog/public/crud"; //display modal form for MyItem editing $(document).on('click','.open_modal',function(){ var MyItem_id = $(this).val(); $.get(url + '/' + MyItem_id, function (data) { //success data console.log(data); $('#MyItem_id').val(data.id); $('#name').val(data.name); $('#comment').val(data.comment); $('#laracrud-btnsave').val("update"); $('#laravelmodel').modal('show'); }) }); //display modal form for creating new MyItem $('#laravel-addrecord').click(function(){ $('#laracrud-btnsave').val("add"); $('#laraliveForm').trigger("reset"); $('#laravelmodel').modal('show'); }); //delete MyItem and remove it from list $(document).on('click','.delete-MyItem',function(){ var MyItem_id = $(this).val(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') } }) $.ajax({ type: "DELETE", url: url + '/' + MyItem_id, success: function (data) { console.log(data); $("#MyItem" + MyItem_id).remove(); }, error: function (data) { console.log('Error:', data); } }); }); $("#laracrud-btnsave").click(function (e) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') } }) e.preventDefault(); var myformdata = { name: $('#name').val(), comment: $('#comment').val(), } var state = $('#laracrud-btnsave').val(); var type = "POST"; var MyItem_id = $('#MyItem_id').val();; var my_url = url; if (state == "update"){ type = "PUT"; my_url += '/' + MyItem_id; } console.log(myformdata); $.ajax({ type: type, url: my_url, data: myformdata, dataType: 'json', success: function (data) { console.log(data); var MyItem = '<tr id="MyItem' + data.id + '"><td>' + data.id + '</td><td>' + data.name + '</td><td>' + data.comment + '</td>'; MyItem += '<td><button class="btn btn-warning btn-detail open_modal" value="' + data.id + '">Edit</button>'; MyItem += ' <button class="btn btn-danger btn-delete delete-MyItem" value="' + data.id + '">Delete</button></td></tr>'; if (state == "add"){ $('#MyItems-list').append(MyItem); }else{ $("#MyItem" + MyItem_id).replaceWith( MyItem ); } $('#laraliveForm').trigger("reset"); $('#laravelmodel').modal('hide') }, error: function (data) { console.log('Error:', data); } }); });
Step5: Add Routes
In routes using laravel, I define all simple functionality for handling jquery ajax call request such as view MyItem, simple read MyItem comment, create new MyItem, update each MyItem and delete MyItem. All the crud oeration activity will be done by using jquery ajax in Laravel.
use Illuminate\Http\Request; Route::get('MyItemajaxcrud', function () { $MyItems = App\MyItem::all(); return view('ajax.index')->with('MyItems',$MyItems); }); Route::get('MyItemajaxcrud/{MyItem_id?}',function($MyItem_id){ $MyItem = App\MyItem::find($MyItem_id); return response()->json($MyItem); }); Route::post('MyItemajaxcrud',function(Request $request){ $MyItem = App\MyItem::create($request->input()); return response()->json($MyItem); }); Route::put('MyItemajaxcrud/{MyItem_id?}',function(Request $request,$MyItem_id){ $MyItem = App\MyItem::find($MyItem_id); $MyItem->name = $request->name; $MyItem->comment = $request->comment; $MyItem->save(); return response()->json($MyItem); }); Route::delete('MyItemajaxcrud/{MyItem_id?}',function($MyItem_id){ $MyItem = App\MyItem::destroy($MyItem_id); return response()->json($MyItem); });