Laravel 5 Ajax CRUD example to build web application without page refresh.
In my last tutorial, i had done CRUD application in Laravel MVC without ajax request, now i am going to tell you how to build CRUD web application without page refresh in Laravel using ajax.
Before this, you should familiar about ajax request, ajax is basically used for affecting webpages without reloading them.
Step 1: Install Laravel 5.2In this step you will have to install fresh laravel project in your system.
composer create-project --prefer-dist laravel/laravel blog "5.2.*"Step 2: Create a Product Table and Model
In this step you will create a product table so for creating table follow the simple step which is mention below.First create migration for products table using Laravel 5 php artisan command,so first run this command -
php artisan make:migration create_products_table
Now you will get a migration file in following path database/migrations and you will have to simply put following code in migration file to create products table.
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Database\Migrations\Migration;
- class CreateProductsTable extends Migration
- {
- public function up()
- {
- Schema::create('products', function (Blueprint $table) {
- $table->increments('id');
- $table->string('name');
- $table->text('details');
- $table->timestamps();
- });
- }
- public function down()
- {
- Schema::drop("products");
- }
- }
Now run php artisan migrate
command to create a product table.
Create a model for product table.
- namespace App;
- use Illuminate\Database\Eloquent\Model;
- class Product extends Model
- {
- public $fillable = ['name','details'];
- }
Now Create a directory ajax and within this directory create a view file index.blade.php
- <html>
- <head>
- <title>Laravel CRUD Application using Ajax without Reloading Page</title>
- <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
- </head>
- <body>
- <div class="container">
- <div class="panel panel-primary">
- <div class="panel-heading">Laravel CRUD Application using Ajax without Reloading Page
- <button id="btn_add" name="btn_add" class="btn btn-default pull-right">Add New Product</button>
- </div>
- <div class="panel-body">
- <table class="table">
- <thead>
- <tr>
- <th>ID</th>
- <th>Name</th>
- <th>Details</th>
- <th>Actions</th>
- </tr>
- </thead>
- <tbody id="products-list" name="products-list">
- @foreach ($products as $product)
- <tr id="product{{$product->id}}">
- <td>{{$product->id}}</td>
- <td>{{$product->name}}</td>
- <td>{{$product->details}}</td>
- <td>
- <button class="btn btn-warning btn-detail open_modal" value="{{$product->id}}">Edit</button>
- <button class="btn btn-danger btn-delete delete-product" value="{{$product->id}}">Delete</button>
- </td>
- </tr>
- @endforeach
- </tbody>
- </table>
- </div>
- </div>
- <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
- <h4 class="modal-title" id="myModalLabel">Product</h4>
- </div>
- <div class="modal-body">
- <form id="frmProducts" name="frmProducts" class="form-horizontal" novalidate="">
- <div class="form-group error">
- <label for="inputName" class="col-sm-3 control-label">Name</label>
- <div class="col-sm-9">
- <input type="text" class="form-control has-error" id="name" name="name" placeholder="Product Name" value="">
- </div>
- </div>
- <div class="form-group">
- <label for="inputDetail" class="col-sm-3 control-label">Details</label>
- <div class="col-sm-9">
- <input type="text" class="form-control" id="details" name="details" placeholder="details" value="">
- </div>
- </div>
- </form>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-primary" id="btn-save" value="add">Save changes</button>
- <input type="hidden" id="product_id" name="product_id" value="0">
- </div>
- </div>
- </div>
- </div>
- </div>
- <meta name="_token" content="{!! csrf_token() !!}" />
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
- <script src="{{asset('js/ajaxscript.js')}}"></script>
- </body>
- </html>
Now in this step create a ajaxscript.js
file in following path public/js/ajaxscript.js
- var url = "http://localhost:8080/blog/public/productajaxCRUD";
- //display modal form for product editing
- $(document).on('click','.open_modal',function(){
- var product_id = $(this).val();
- $.get(url + '/' + product_id, function (data) {
- //success data
- console.log(data);
- $('#product_id').val(data.id);
- $('#name').val(data.name);
- $('#details').val(data.details);
- $('#btn-save').val("update");
- $('#myModal').modal('show');
- })
- });
- //display modal form for creating new product
- $('#btn_add').click(function(){
- $('#btn-save').val("add");
- $('#frmProducts').trigger("reset");
- $('#myModal').modal('show');
- });
- //delete product and remove it from list
- $(document).on('click','.delete-product',function(){
- var product_id = $(this).val();
- $.ajaxSetup({
- headers: {
- 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
- }
- })
- $.ajax({
- type: "DELETE",
- url: url + '/' + product_id,
- success: function (data) {
- console.log(data);
- $("#product" + product_id).remove();
- },
- error: function (data) {
- console.log('Error:', data);
- }
- });
- });
- //create new product / update existing product
- $("#btn-save").click(function (e) {
- $.ajaxSetup({
- headers: {
- 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
- }
- })
- e.preventDefault();
- var formData = {
- name: $('#name').val(),
- details: $('#details').val(),
- }
- //used to determine the http verb to use [add=POST], [update=PUT]
- var state = $('#btn-save').val();
- var type = "POST"; //for creating new resource
- var product_id = $('#product_id').val();;
- var my_url = url;
- if (state == "update"){
- type = "PUT"; //for updating existing resource
- my_url += '/' + product_id;
- }
- console.log(formData);
- $.ajax({
- type: type,
- url: my_url,
- data: formData,
- dataType: 'json',
- success: function (data) {
- console.log(data);
- var product = '<tr id="product' + data.id + '"><td>' + data.id + '</td><td>' + data.name + '</td><td>' + data.details + '</td>';
- product += '<td><button class="btn btn-warning btn-detail open_modal" value="' + data.id + '">Edit</button>';
- product += ' <button class="btn btn-danger btn-delete delete-product" value="' + data.id + '">Delete</button></td></tr>';
- if (state == "add"){ //if user added a new record
- $('#products-list').append(product);
- }else{ //if user updated an existing record
- $("#product" + product_id).replaceWith( product );
- }
- $('#frmProducts').trigger("reset");
- $('#myModal').modal('hide')
- },
- error: function (data) {
- console.log('Error:', data);
- }
- });
- });
In routes, I define all functionality for handling ajax request such as listing product, read product details, create product, update product and delete product. All the activity will be done by using ajax in Laravel.
- use Illuminate\Http\Request;
- Route::get('productajaxCRUD', function () {
- $products = App\Product::all();
- return view('ajax.index')->with('products',$products);
- });
- Route::get('productajaxCRUD/{product_id?}',function($product_id){
- $product = App\Product::find($product_id);
- return response()->json($product);
- });
- Route::post('productajaxCRUD',function(Request $request){
- $product = App\Product::create($request->input());
- return response()->json($product);
- });
- Route::put('productajaxCRUD/{product_id?}',function(Request $request,$product_id){
- $product = App\Product::find($product_id);
- $product->name = $request->name;
- $product->details = $request->details;
- $product->save();
- return response()->json($product);
- });
- Route::delete('productajaxCRUD/{product_id?}',function($product_id){
- $product = App\Product::destroy($product_id);
- return response()->json($product);
- });
Click here to see demo of this application how crud work in Laravel with ajax....