I am Developer

1591072396

Laravel Ajax CRUD Example Tutorial

Laravel makes ajax CRUD Application with bootstrap modals. In this tutorial, we will explain to you, how you can create your first ajax crud application with bootstrap modals in laravel.

This is originally published at https://www.tutsmake.com/laravel-6-create-ajax-crud-application-example/

In this post, we will use bootstrap modal and jquery ajax for creating laravel ajax crud application. In this example, we will show users list with pagination and also get and send data from database using ajax.

At the end of this post, we will attach a live demo button. click on live demo button and test demo laravel ajax crud application in your hand

Laravel Ajax CRUD Application with Bootstrap Modal

Just follow the below steps and you can easily create your first crud application with laravel framework:

  • First Install New Laravel Setup
  • Configure .env file
  • Create One Model and Migration
  • Make Route
  • Generate(create) Controller
  • Create Blade View
  • Start Development Server
  • Conclusion

1). First Install New Laravel Setup

In this step, we will download a new laravel setup. Use the below following command and download it :

composer create-project --prefer-dist laravel/laravel blog

2). Configure .env file

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 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

3). Make 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');

4). 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)
    {  
        $userId = $request->user_id;
        $user   =   User::updateOrCreate(['id' => $userId],
                    ['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);
    }
}

5). 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 - Tutsmake.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.tutsmake.com" target="_blank" >TutsMake</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.tutsmake.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><a href="javascript:void(0)" id="edit-user" data-id="{{ $u_info->id }}" class="btn btn-info">Edit</a></td>
                 <td>
                  <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>
        <div class="modal-body">
            <form id="userForm" name="userForm" class="form-horizontal">
               <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>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-primary" id="btn-save" value="create">Save changes
            </button>
        </div>
    </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");
        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.tutsmake.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><a href="javascript:void(0)" id="edit-user" data-id="' + data.id + '" class="btn btn-info">Edit</a></td>';
              user += '<td><a href="javascript:void(0)" id="delete-user" data-id="' + data.id + '" class="btn btn-danger delete-user">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>

6). Run 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 application.

What is GEEK

Buddha Community

Laravel Ajax CRUD Example Tutorial

Laravel AJAX CRUD Example Tutorial

Hello Guys,

Today I will show you how to create laravel AJAX CRUD example tutorial. In this tutorial we are implements ajax crud operation in laravel. Also perform insert, update, delete operation using ajax in laravel 6 and also you can use this ajax crud operation in laravel 6, laravel 7. In ajax crud operation we display records in datatable.

Read More : Laravel AJAX CRUD Example Tutorial

https://www.techsolutionstuff.com/post/laravel-ajax-crud-example-tutorial


Read Also : Read Also : Laravel 6 CRUD Tutorial with Example

https://techsolutionstuff.com/post/laravel-6-crud-tutorial-with-example

#laravel ajax crud example tutorial #ajax crud example in laravel #laravel crud example #laravel crud example with ajax #laravel #php

I am Developer

1617089618

Laravel 8 Tutorial for Beginners

Hello everyone! I just updated this tutorial for Laravel 8. In this tutorial, we’ll go through the basics of the Laravel framework by building a simple blogging system. Note that this tutorial is only for beginners who are interested in web development but don’t know where to start. Check it out if you are interested: Laravel Tutorial For Beginners

Laravel is a very powerful framework that follows the MVC structure. It is designed for web developers who need a simple, elegant yet powerful toolkit to build a fully-featured website.

Recommended:-Laravel Try Catch

#laravel 8 tutorial #laravel 8 tutorial crud #laravel 8 tutorial point #laravel 8 auth tutorial #laravel 8 project example #laravel 8 tutorial for beginners

Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

Laravel 6 CRUD Tutorial with Example

In this example, I will show you to how to make simple laravel CRUD(insert, update, delete or listing) operations with example.

Insert Update Delete module is primary requirement for each project,you will understand how to use route, controller, blade files, model and migration for crud operation in laravel 6.

We just need to follow below step and you will get basic CRUD using controller, model, route, bootstrap 4 and blade. If you follow below step then definatly you will get proper output.

Read More : Laravel 6 CRUD Tutorial with Example

https://www.techsolutionstuff.com/post/laravel-6-crud-tutorial-with-example

#laravel 6 crud tutorial with example #laravel 6 tutorial #crud tutorial #laravel #php #jquery

Laravel 8 CRUD Operation Example

Hello Friend,

As you know Laravel 8 already officially released and today I will show you how to create CRUD operation in laravel 8, I have already perform many CRUD operations in my previous post like CRUD operation in ajax, CRUD operation in laravel 6 etc. So, today I will give you laravel 8 CRUD application example.

Laravel 8 CRUD Operation Example

https://websolutionstuff.com/post/laravel-8-crud-operation-example

#laravel #php #laravel 8 crud operation example #crud operation #laravel 8 crud tutorial #crud operation in laravel 8