Laravel is the most popular framework of PHP. laravel better than another PHP framework because it handles the command base. so let us see about laravel 6.0 crud tutorial with ajax example. it was released on Sept 03, 2019.

Now, we follow the below step for creating the Laravel 6.0 CRUD Operation With Ajax Example.

laravel 6.0 crud tutorial, laravel 6.0 crud example, Laravel 6.0 CRUD (Create Read Update Delete) Operation For Beginners With Example, CRUD Operations Laravel 6.0, Laravel 6.0 CRUD Operation with Example, laravel 6.0 crud, laravel crud operation, laravel crud tutorial, laravel crud operations, laravel, laravel crud example,  Laravel crud operation  with ajax example.

Overview

Step 1: Install Laravel 6.0

Step 2: Setting Database Configuration

Step 3: Create Table using migration

Step 4: Create Resource Route in web.php file

Step 5: Create Model and Controller

Step 6: Create Blade Files

Step 1 : Install Laravel 6.0

We are going to install laravel 6.0, so first open the command prompt or terminal and go to go to xampp htdocs folder directory using the command prompt. after then run the below command.

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

Step 2: Setting Database Configuration

After complete installation of laravel. we have to database configuration. now we will open the .env file and change the database name, username, password in the .env file. See below changes in a .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name(larave6_ajax_crud)
DB_USERNAME=Enter_Your_Database_Username(root)
DB_PASSWORD=Enter_Your_Database_Password(root)

Step 3: Create Table using migration

Now, We need to create a migration. so we will below command using create the students table migration.

php artisan make:migration create_students_table --create=students

After complete migration. we need below changes in the database/migrations/create_students_table file.

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->text('address');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}
?>

Run the below command. after the changes above file.

php artisan migrate

Step 4: Create a Custom Route in web.php file

We have to need put below route in routes/web.php file.

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
   // return view('welcome');	
});
Route::get('student','StudentController@index');
Route::post('student','StudentController@store')->name('student.store');
Route::get('student/{id}/edit', 'StudentController@edit')->name('student.edit');
Route::post('student/update', 'StudentController@update')->name('student.update');
Route::get('student/{id}/delete', 'StudentController@destroy')->name('student.delete');

?>

Step 5: Create Model and Controller

Here below command help to create the controller and model.

php artisan make:controller StudentController --resource --model=Student

Student.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    //
	protected $fillable = [
        'first_name','last_name', 'address'
    ];
}
?>

StudentController.php

<?php

namespace App\Http\Controllers;

use App\Student;
use Illuminate\Http\Request;
use Response;
class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
		$data['students'] = Student::orderBy('id','desc')->paginate(5);   
        return view('student.list',$data);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {		
		$student = new Student([
            'first_name' => $request->post('txtFirstName'),
            'last_name'=> $request->post('txtLastName'),
            'address'=> $request->post('txtAddress')
        ]);
		$student->save();    
        return Response::json($student);
    }
    /**
     * Display the specified resource.
     *
     * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function show(Student $student)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
		$where = array('id' => $id);
        $student  = Student::where($where)->first();
 
        return Response::json($student);
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        //
		$student = Student::find($request->post('hdnStudentId'));
        $student->first_name = $request->post('txtFirstName');
        $student->last_name = $request->post('txtLastName');
        $student->address = $request->post('txtAddress');
        $student->update();
		return Response::json($student);
		
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        $student = Student::where('id',$id)->delete();
        return Response::json($student);
    }
}
?>

Step 6: Create Blade Files

So finally, first we will create the new directory "resources/views/layouts" and that directory in create a "resources/views/layouts/app.blade.php" file. and the second time we will create a list.blade.php in the "resources/ views/student/" directory.

app.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
</head>
<body>
<div class="container">
    @yield('content')
</div>
</body>
</html>

list.blade.php

@extends('layouts.app')
@section('content')
    <div class="row">
        <div class="col-lg-11">
                <h2>Laravel 6.0 Ajax CRUD Example</h2>
        </div>
        <div class="col-lg-1">
            <a class="btn btn-success" href="#" data-toggle="modal" data-target="#addModal">Add</a>
        </div>
    </div>
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif
    <table class="table table-bordered" id="studentTable">
		<thead>
			<tr>
				<th>id</th>
				<th>First Name</th>
				<th>Last Name</th>
				<th>Address</th>
				<th width="280px">Action</th>
			</tr>
		</thead>	
		<tbody>
        @foreach ($students as $student)
            <tr id="{{ $student->id }}">
                <td>{{ $student->id }}</td>
                <td>{{ $student->first_name }}</td>
                <td>{{ $student->last_name }}</td>
                <td>{{ $student->address }}</td>
                <td>
		     <a data-id="{{ $student->id }}" class="btn btn-primary btnEdit">Edit</a>
		     <a data-id="{{ $student->id }}" class="btn btn-danger btnDelete">Delete</button>
                </td>
            </tr>
        @endforeach
		</tbody>
    </table>
	

<!-- Add Student Modal -->
<div id="addModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Student Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Add New Student</h4>
      </div>
	  <div class="modal-body">
		<form id="addStudent" name="addStudent" action="{{ route('student.store') }}" method="post">
			@csrf
			<div class="form-group">
				<label for="txtFirstName">First Name:</label>
				<input type="text" class="form-control" id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
			</div>
			<div class="form-group">
				<label for="txtLastName">Last Name:</label>
				<input type="text" class="form-control" id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
			</div>
			<div class="form-group">
				<label for="txtAddress">Address:</label>
				<textarea class="form-control" id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></textarea>
			</div>
			<button type="submit" class="btn btn-primary">Submit</button>
		</form>
	  </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>	
<!-- Update Student Modal -->
<div id="updateModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Student Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Update Student</h4>
      </div>
	  <div class="modal-body">
		<form id="updateStudent" name="updateStudent" action="{{ route('student.update') }}" method="post">
			<input type="hidden" name="hdnStudentId" id="hdnStudentId"/>
			@csrf
			<div class="form-group">
				<label for="txtFirstName">First Name:</label>
				<input type="text" class="form-control" id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
			</div>
			<div class="form-group">
				<label for="txtLastName">Last Name:</label>
				<input type="text" class="form-control" id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
			</div>
			<div class="form-group">
				<label for="txtAddress">Address:</label>
				<textarea class="form-control" id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></textarea>
			</div>
			<button type="submit" class="btn btn-primary">Submit</button>
		</form>
	  </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>	

<script>
  $(document).ready(function () {
	//Add the Student  
	$("#addStudent").validate({
		 rules: {
				txtFirstName: "required",
				txtLastName: "required",
				txtAddress: "required"
			},
			messages: {
			},
 
		 submitHandler: function(form) {
		  var form_action = $("#addStudent").attr("action");
		  $.ajax({
			  data: $('#addStudent').serialize(),
			  url: form_action,
			  type: "POST",
			  dataType: 'json',
			  success: function (data) {
				  var student = '<tr id="'+data.id+'">';
				  student += '<td>' + data.id + '</td>';
				  student += '<td>' + data.first_name + '</td>';
				  student += '<td>' + data.last_name + '</td>';
				  student += '<td>' + data.address + '</td>';
				  student += '<td><a data-id="' + data.id + '" class="btn btn-primary btnEdit">Edit</a>&nbsp;&nbsp;<a data-id="' + data.id + '" class="btn btn-danger btnDelete">Delete</a></td>';
				  student += '</tr>';            
				  $('#studentTable tbody').prepend(student);
				  $('#addStudent')[0].reset();
				  $('#addModal').modal('hide');
			  },
			  error: function (data) {
			  }
		  });
		}
	});
  
 
    //When click edit student
    $('body').on('click', '.btnEdit', function () {
      var student_id = $(this).attr('data-id');
      $.get('student/' + student_id +'/edit', function (data) {
          $('#updateModal').modal('show');
          $('#updateStudent #hdnStudentId').val(data.id); 
          $('#updateStudent #txtFirstName').val(data.first_name);
          $('#updateStudent #txtLastName').val(data.last_name);
          $('#updateStudent #txtAddress').val(data.address);
      })
   });
    // Update the student
	$("#updateStudent").validate({
		 rules: {
				txtFirstName: "required",
				txtLastName: "required",
				txtAddress: "required"
				
			},
			messages: {
			},
 
		 submitHandler: function(form) {
		  var form_action = $("#updateStudent").attr("action");
		  $.ajax({
			  data: $('#updateStudent').serialize(),
			  url: form_action,
			  type: "POST",
			  dataType: 'json',
			  success: function (data) {
				  var student = '<td>' + data.id + '</td>';
				  student += '<td>' + data.first_name + '</td>';
				  student += '<td>' + data.last_name + '</td>';
				  student += '<td>' + data.address + '</td>';
				  student += '<td><a data-id="' + data.id + '" class="btn btn-primary btnEdit">Edit</a>&nbsp;&nbsp;<a data-id="' + data.id + '" class="btn btn-danger btnDelete">Delete</a></td>';
				  $('#studentTable tbody #'+ data.id).html(student);
				  $('#updateStudent')[0].reset();
				  $('#updateModal').modal('hide');
			  },
			  error: function (data) {
			  }
		  });
		}
	});		
		
   //delete student
	$('body').on('click', '.btnDelete', function () {
      var student_id = $(this).attr('data-id');
      $.get('student/' + student_id +'/delete', function (data) {
          $('#studentTable tbody #'+ student_id).remove();
      })
   });	
	
});	  
</script>
@endsection

We can start the server and run this example using the below command.

php artisan serve

Now we will run our example using the below Url in the browser.

http://127.0.0.1:8000/student