Laravel 6 jQuery Ajax CRUD tutorial

Laravel 6 jQuery Ajax CRUD tutorial


jQuery is a popular js library for the web developer community. In modern Js trend, the use of jQuery is reduced a little bit but someone still loves jQuery to do something in their web application. If you are searching a step by step tutorial on Laravel jQuery CRUD than you are in the right place and reading a step by step tutorial on how to make CRUD app using Laravel and jQuery. In this tutorial post, I'll use the latest Laravel version 6 but the complete post is version independent. You can do the exactly the same behaviour in your Laravel application whatever Laravel version you are using now.

 

Table of Content

  • Define routes
  • Make a model
  • Make a controller
  • Make a view for CRUD operation

 

Define Routes

Define these routes in your web.php file or routes.php file if you are using an old version of Laravel framework.

Route::get('contacts','ContactController@getIndex');
Route::post('contacts','ContactController@postStore');
Route::get('contacts/data','ContactController@getData');
Route::post('contact/update','ContactController@postUpdate');
Route::post('contact/delete','ContactController@postDelete');

 

Make a model

Make a contact model for database operation of our CRUD app. Our table name is contacts with fields id, name, phone. Here timestamp is false because we are not included created_at and update_at fields in our table which are required by default for a Laravel model.

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Contact extends Model

{

    public $timestamps = false;

    protected $table = 'contacts';

    protected $fillable = ['name','phone'];

}

 

Make a controller

Make a controller name with ContactController by artisan command php artisan make:controller ContactController and do the code for CRUD operation.

<?php namespace App\Http\Controllers;

use App\Http\Requests;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use App\Contact;




class ContactController extends Controller

{

    public function __construct()

    {

        $this->middleware('auth');

    }



    public function getIndex()

    {

        return view('admin.contacts');

    }



    public function getData()

    {

        return Contact::all();

    }



    public function postStore(Request $request)

    {

        return Contact::create($request->all());

    }



    public function postUpdate(Request $request)

    {

        if($request->has('id')){

          $record = Contact::find($request->input('id'));

          $record->update($request->all());

        }

    }



    public function postDelete(Request $request)

    {

        if($request->has('id')){

          $record = Contact::where('id',$request->input('id'));

          $record->delete();

        }
    }

}

 

Make a view for CRUD operation

Now the final part, create a contacts.blade.php file inside the resources/views directory and do markup for jQuery Ajax CRUD operation. in this single view, we'll do create, read, update and delete operation with jQuery Ajax. Let's do that.

@extends('app')
@section('content')
    <div class="container">

        <div class="col-md-12">
            <div class="clearfix">
                <span>Laravel - jQuery CRUD</span>
                <a class="btn btn-success btn-sm pull-right" onclick="create()">Add New</a>
            </div>

            <!--data listing table-->
            <table class="table table-bordered table-striped table-condensed">
                <thead>
                <tr>
                    <td>ID</td>
                    <td>NAME</td>
                    <td>EMAIL</td>
                    <td>PHONE</td>
                    <td>ACTION</td>
                </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
            <!--data listing table-->

        </div>

    </div>

    <!-- modal -->
    <div class="modal fade" id="modal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close"
                            data-dismiss="modal" aria-hidden="true">&times;
                    </button>
                    <h4 class="modal-title"></h4>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="id">
                    <div class="form-group">
                        <label>Name</label>
                        <input class="form-control input-sm" type="text" name="name">
                    </div>
                    <div class="form-group">
                        <label>E-mail</label>
                        <input class="form-control input-sm" type="email" name="email">
                    </div>
                    <div class="form-group">
                        <label>Phone</label>
                        <input class="form-control input-sm" type="text" name="phone">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                    <button type="button" class="btn btn-primary btnSave"
                            onClick="store()">Save
                    </button>
                    <button type="button" class="btn btn-primary btnUpdate"
                            onClick="update()">Update
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->



    <script>
        var adminUrl = '';
        var _modal = $('#modal');
        var btnSave = $('.btnSave');
        var btnUpdate = $('.btnUpdate');

        $.ajaxSetup({
            headers: {'X-CSRF-Token': ''}
        });


        function getRecords() {
            $.get(adminUrl + '/contacts/data')
                .success(function (data) {
                    var html='';
                    data.forEach(function(row){
                        html += '<tr>'
                        html += '<td>' + row.id + '</td>'
                        html += '<td>' + row.name + '</td>'
                        html += '<td>' + row.email + '</td>'
                        html += '<td>' + row.phone + '</td>'
                        html += '<td>'
                        html += '<button type="button" class="btn btn-xs btn-warning btnEdit" title="Edit Record" >Edit</button>'
                        html += '<button type="button" class="btn btn-xs btn-danger btnDelete" data-id="' + row.id + '" title="Delete Record">Delete</button>'
                        html += '</td> </tr>';
                    })

                    $('table tbody').html(html)
                })
        }
        getRecords()

        function reset() {
            _modal.find('input').each(function () {
                $(this).val(null)
            })
        }

        function getInputs() {
            var id = $('input[name="id"]').val()
            var name = $('input[name="name"]').val()
            var email = $('input[name="email"]').val()
            var phone = $('input[name="phone"]').val()

            return {id: id, name: name, email: email, phone: phone}
        }

        function create() {
            _modal.find('.modal-title').text('New Contact');
            reset();
            _modal.modal('show')
            btnSave.show()
            btnUpdate.hide()
        }

        function store(){
            if(!confirm('Are you sure?')) return;
            $.ajax({
                method: 'POST',
                url: adminUrl + '/contacts/store',
                data: getInputs(),
                dataType: 'JSON',
                success: function () {
                    console.log('inserted')
                    reset()
                    _modal.modal('hide')
                    getRecords();
                }
            })
        }

        $('table').on('click', '.btnEdit', function () {
            _modal.find('.modal-title').text('Edit Contact')
            _modal.modal('show')

            btnSave.hide()
            btnUpdate.show()

            var id = $(this).parent().parent().find('td').eq(0).text()
            var name = $(this).parent().parent().find('td').eq(1).text()
            var email = $(this).parent().parent().find('td').eq(2).text()
            var phone = $(this).parent().parent().find('td').eq(3).text()

            $('input[name="id"]').val(id)
            $('input[name="name"]').val(name)
            $('input[name="email"]').val(email)
            $('input[name="phone"]').val(phone)
        })

        function update(){
            if(!confirm('Are you sure?')) return;
            $.ajax({
                method: 'POST',
                url: adminUrl + '/contacts/update',
                data: getInputs(),
                dataType: 'JSON',
                success: function () {
                    console.log('updated')
                    reset()
                    _modal.modal('hide')
                    getRecords();
                }
            })
        }


        $('table').on('click', '.btnDelete', function () {
            if(!confirm('Are you sure?')) return;

            var id = $(this).data('id');
            var data={id:id}

            $.ajax({
                method: 'POST',
                url: adminUrl + '/contacts/delete',
                data:data,
                dataType: 'JSON',
                success: function () {
                    console.log('deleted');
                    getRecords();
                }
            })

        })

    </script>

@endsection

 

Our Laravel JQuery Ajax CRUD app is ready to use. Open your browser and browser example.com/contacts and test create, read, update and delete records.

 

Hope this step by step Laravel jQuery ajax tutorial will help you to make Laravel jQuery Ajax CRUD system in your web application. If this is helpful to you then please share this with others.


Share on


sidebar ad


Related Post


Laravel Barcode generation tutorial

Laravel Inertia Js CRUD tutorial

Laravel 7 CRUD tutorial

Laravel Livewire CRUD tutorial

Laravel 6 CRUD tutorial step by step

Laravel 6 AngularJs CRUD tutorial