Laravel 6 Ajax CRUD Operations Tutorial

Laravel 6 Ajax CRUD Operations Tutorial

In this post, you'll learn step by step Ajax CRUD Operations in Laravel 6 with modal & pagination.

Originally published at https://itsolutionstuff.com

We will create Jquery Ajax CRUD with modals using Datatables js in Laravel 6. we will simply write Jquery Ajax request for crud with yajra datatable Laravel 6.

We will use yajra datatable to list a records with pagination, sorting and filter (search). We will use bootstrap modal for create new records and update new records. we will use resource routes to create crud (create read update delete) application in Laravel 6.

I will provide you step by step guide to create ajax crud example with Laravel 6. you just need to follow few step to get c.r.u.d with modals and ajax. You can easily use with your Laravel 6 project and easy to customize it.

You can see bellow preview of ajax crud app.

Step 1: Install Laravel 6

First of all we need to get fresh Laravel 6 version application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog
Step 2: Install Yajra Datatable

We need to install yajra datatable composer package for datatable, so you can install using following command:

composer require yajra/laravel-datatables-oracle

After that you need to set providers and alias.

config/app.php

.....
'providers' => [
	....
	Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
	....
	'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....

Read Also: Laravel 6 CRUD Application Tutorial

Step 3: Database Configuration

In second step, we will make database configuration for example database name, username, password etc for our crud application of Laravel 6. So let's open .env file and fill all details like as bellow:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 4: Create Migration Table

we are going to create ajax crud application for product. so we have to create migration for "products" table using Laravel 6 php artisan command, so first fire bellow command:

php artisan make:migration create_products_table --create=products

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create products table.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('detail');
$table->timestamps();
});
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('products');
}

}

Now you have to run this migration by following command:

php artisan migrate
Step 5: Create Route

Here, we need to add resource route for product ajax crud application. so open your "routes/web.php" file and add following route.

routes/web.php

Route::resource('ajaxproducts','ProductAjaxController');

Step 6: Add Controller and Model

In this step, now we should create new controller as ProductAjaxController. So run bellow command and create new controller.

So, let's copy bellow code and put on ProductAjaxController.php file.

app/Http/Controllers/ProductAjaxController.php

<?php

namespace App\Http\Controllers;

use App\Product;
use Illuminate\Http\Request;
use DataTables;

class ProductAjaxController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{

    if ($request-&gt;ajax()) {
        $data = Product::latest()-&gt;get();
        return Datatables::of($data)
                -&gt;addIndexColumn()
                -&gt;addColumn('action', function($row){

                       $btn = '&lt;a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row-&gt;id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editProduct"&gt;Edit&lt;/a&gt;';

                       $btn = $btn.' &lt;a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row-&gt;id.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteProduct"&gt;Delete&lt;/a&gt;';

                        return $btn;
                })
                -&gt;rawColumns(['action'])
                -&gt;make(true);
    }
  
    return view('productAjax',compact('products'));
}
 
/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    Product::updateOrCreate(['id' =&gt; $request-&gt;product_id],
            ['name' =&gt; $request-&gt;name, 'detail' =&gt; $request-&gt;detail]);        

    return response()-&gt;json(['success'=&gt;'Product saved successfully.']);
}
/**
 * Show the form for editing the specified resource.
 *
 * @param  \App\Product  $product
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $product = Product::find($id);
    return response()-&gt;json($product);
}

/**
 * Remove the specified resource from storage.
 *
 * @param  \App\Product  $product
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    Product::find($id)-&gt;delete();
 
    return response()-&gt;json(['success'=&gt;'Product deleted successfully.']);
}

}

Ok, so after run bellow command you will find "app/Product.php" and put bellow content in Product.php file:

app/Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
protected $fillable = [
'name', 'detail'
];
}

Step 7: Add Blade Files

In last step. In this step we have to create just blade file. so we need to create only one blade file as productAjax.blade.php file.

So let's just create following file and put bellow code.

resources/views/productAjax.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Laravel 6 Ajax CRUD tutorial using Datatable - ItSolutionStuff.com</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="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>

<div class="container">
<h1>Laravel 6 Ajax CRUD tutorial using Datatable - ItSolutionStuff.com</h1>
<a class="btn btn-success" href="javascript:void(0)" id="createNewProduct"> Create New Product</a>
<table class="table table-bordered data-table">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Details</th>
<th width="280px">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

<div class="modal fade" id="ajaxModel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modelHeading"></h4>
</div>
<div class="modal-body">
<form id="productForm" name="productForm" class="form-horizontal">
<input type="hidden" name="product_id" id="product_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>

                &lt;div class="form-group"&gt;
                    &lt;label class="col-sm-2 control-label"&gt;Details&lt;/label&gt;
                    &lt;div class="col-sm-12"&gt;
                        &lt;textarea id="detail" name="detail" required="" placeholder="Enter Details" class="form-control"&gt;&lt;/textarea&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
  
                &lt;div class="col-sm-offset-2 col-sm-10"&gt;
                 &lt;button type="submit" class="btn btn-primary" id="saveBtn" value="create"&gt;Save changes
                 &lt;/button&gt;
                &lt;/div&gt;
            &lt;/form&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

</div>

</body>

<script type="text/javascript">
$(function () {

  $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
});

var table = $('.data-table').DataTable({
    processing: true,
    serverSide: true,
    ajax: "{{ route('ajaxproducts.index') }}",
    columns: [
        {data: 'DT_RowIndex', name: 'DT_RowIndex'},
        {data: 'name', name: 'name'},
        {data: 'detail', name: 'detail'},
        {data: 'action', name: 'action', orderable: false, searchable: false},
    ]
});
 
$('#createNewProduct').click(function () {
    $('#saveBtn').val("create-product");
    $('#product_id').val('');
    $('#productForm').trigger("reset");
    $('#modelHeading').html("Create New Product");
    $('#ajaxModel').modal('show');
});

$('body').on('click', '.editProduct', function () {
  var product_id = $(this).data('id');
  $.get("{{ route('ajaxproducts.index') }}" +'/' + product_id +'/edit', function (data) {
      $('#modelHeading').html("Edit Product");
      $('#saveBtn').val("edit-user");
      $('#ajaxModel').modal('show');
      $('#product_id').val(data.id);
      $('#name').val(data.name);
      $('#detail').val(data.detail);
  })

});

$('#saveBtn').click(function (e) {
    e.preventDefault();
    $(this).html('Sending..');

    $.ajax({
      data: $('#productForm').serialize(),
      url: "{{ route('ajaxproducts.store') }}",
      type: "POST",
      dataType: 'json',
      success: function (data) {
 
          $('#productForm').trigger("reset");
          $('#ajaxModel').modal('hide');
          table.draw();
     
      },
      error: function (data) {
          console.log('Error:', data);
          $('#saveBtn').html('Save Changes');
      }
  });
});

$('body').on('click', '.deleteProduct', function () {
 
    var product_id = $(this).data("id");
    confirm("Are You sure want to delete !");
  
    $.ajax({
        type: "DELETE",
        url: "{{ route('ajaxproducts.store') }}"+'/'+product_id,
        success: function (data) {
            table.draw();
        },
        error: function (data) {
            console.log('Error:', data);
        }
    });
});

});
</script>
</html>

Now you can test it by using following command:

php artisan serve

Now you can open bellow URL on your browser:

Read Also: Laravel 6 Resize Image Before Upload Example

http://localhost:8000/ajaxproducts

You can download code from GitHub

I hope it can help you....

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Further reading

☞ Tutorial Laravel 6 with Docker and Docker-Compose

☞ Laravel 6 Release New Features and Upgrade

☞ What's New in Laravel 6.0?

☞ Laravel 6 CRUD Application Tutorial


Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]

Which is the best PHP Web Development Company in India?

Which is the best PHP Web Development Company in India?

Many experienced players prefer to give it a go ahead with PHP for their web development needs because of the simplicity that PHP provides. PHP is loaded with features that many other languages lack and those pre-defined features can bring new functionalities and finishing touch to your existing or new website that you are looking forward to create. Wouldn’t it be great to get the best PHP Web Development Company for your project; we have a reputation as few of the leading firms in IT industry when it comes to PHP development.

Perks you should keep an eye out for before considering to outsource project to any web development company:

1. Company’s Reputation- It is very important to know about the previous projects that the company has delivered and the success rate of those products. You can visit company’s website for client testimonials or can google reviews given to them by genuine clients. We follow transparency, you can contact our previous clients and let them tell you how their experience was while working with us.

2. Technical Skill set and Expertise- You should select a company that has multiple resource pool of expert and technically sound developers. Our developers are experienced with different PHP frameworks and are exceptionally good with writing bug free codes. You can also hire PHP developer in India from us, as our developers have on hand experience in PHP development (core and frameworks)

3. The Budget- Costing has always played as one of the most important roles in every business deal. We provide competitive pricing with no hidden cost guaranteed. With us you can expect your project to be in best quality with no compromise to be made even with the best price in the market.

Why Data EximIT is the best PHP web development company in India?

Here are some of the features that might love about Data EximIT:

 Reputation of Data EximIT is wonderful among the previous clients.

 We have around 87% of retention ratio of clients.

 We were time committed, means every milestone was achieved before or on time.

 Data EximIT follows Agile development so it was the best possible methodology.

 We have huge team with different expertise over multiple PHP frameworks, so you are provided with ample to options to choose from.

 We are very active in communication part. Method or time of communication was never an issue at Data EximIT.

 We have some of the best designers to ensure that your project not only functions but also looks and feels fabulous.

 We provided customers with best costing without compromising on the quality at all.

 We also provide dedicated PHP developer or team of PHP developers on hire for your project.

Data EximIT is where customers feel confident to come up with idea and leave with fully functioning & best in quality projects. You can also avail our developers at your requested site location if you decide to hire PHP developers in India from us.

Feel free to contact our experts and let success reach you by working with the best PHP web development company.

Laravel 6 Ajax Request Tutorial

Laravel 6 Ajax Request Tutorial

In this post, you'll learn how to write jquery ajax form submit in Laravel 6. We will write Jquery Ajax post request Laravel 6. We will protect csrf token with Ajax request in Laravel 6. I will give you very simple example of Laravel 6 Ajax post request tutorial.

You can easily use Ajax get request, Ajax post request, Ajax put request, Ajax delete request ect with Laravel 6.

Ajax request is a basic requirement of any PHP project, we are always looking for without page refresh data should store in database and it's possible only by Jquery Ajax request. same thing if you need to write ajax form submit in Laravel 6 then i will help you how you can pass data with ajax request and get on controller.

If you want to add ajax request with validation then you can follow this article: Laravel 6 Ajax Form Validation

You have to just do three things to understand how to use ajax request in Laravel 6, so just follow this three step and you will learn how to use Ajax request in your Laravel 6 application.

Step 1: Create Routes

First thing is we put two routes in one for displaying view and another for post Ajax. So simple add both routes in your route file.

routes/web.php

Route::get('ajaxRequest', '[email protected]');
Route::post('ajaxRequest', '[email protected]')->name('ajaxRequest.post');

Step 2: Create Controller

Same things as above for routes, here we will add two new method for routes. One will handle view layout and another for post ajax request method, so let's add bellow:

app/Http/Controllers/HomeController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class AjaxController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function ajaxRequest()
{
return view('ajaxRequest');
}

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function ajaxRequestPost(Request $request)
{
    $input = $request-&gt;all();
    \Log::info($input);

    return response()-&gt;json(['success'=&gt;'Got Simple Ajax Request.']);
}

}

Read Also: Laravel 6 CRUD Application Tutorial

Step 3: Create Blade File

Finally we require to create ajaxRequest.blade.php file and here we will write code of jquery ajax and pass Laravel token. So blade file is very important in ajax request. So let's see bellow file:

resources/views/ajaxRequest.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Laravel 6 Ajax Request example</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>

&lt;div class="container"&gt;
    &lt;h1&gt;Laravel 6 Ajax Request example&lt;/h1&gt;

    &lt;form &gt;

        &lt;div class="form-group"&gt;
            &lt;label&gt;Name:&lt;/label&gt;
            &lt;input type="text" name="name" class="form-control" placeholder="Name" required=""&gt;
        &lt;/div&gt;

        &lt;div class="form-group"&gt;
            &lt;label&gt;Password:&lt;/label&gt;
            &lt;input type="password" name="password" class="form-control" placeholder="Password" required=""&gt;
        &lt;/div&gt;

        &lt;div class="form-group"&gt;
            &lt;strong&gt;Email:&lt;/strong&gt;
            &lt;input type="email" name="email" class="form-control" placeholder="Email" required=""&gt;
        &lt;/div&gt;

        &lt;div class="form-group"&gt;
            &lt;button class="btn btn-success btn-submit"&gt;Submit&lt;/button&gt;
        &lt;/div&gt;

    &lt;/form&gt;
&lt;/div&gt;

</body>
<script type="text/javascript">

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(".btn-submit").click(function(e){

    e.preventDefault();

    var name = $("input[name=name]").val();
    var password = $("input[name=password]").val();
    var email = $("input[name=email]").val();

    $.ajax({
       type:'POST',
       url:"{{ route('ajaxRequest.post') }}",
       data:{name:name, password:password, email:email},
       success:function(data){
          alert(data.success);
       }
    });

});

</script>

</html>

Now you can run your example and see.

You will get output like as bellow:

Output

[2019-09-17 03:54:19] local.INFO: array (
'name' => 'Hardik Savani',
'password' => '123456',
'email' => '[email protected]',
)

I hope it can help you

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Further reading

☞ Tutorial Laravel 6 with Docker and Docker-Compose

☞ Laravel 6 CRUD Application Tutorial

☞ What's New in Laravel 6.0?

Originally published https://itsolutionstuff.com