Laravel 7 CRUD Operation With Ajax Example – onlinecode

Laravel 7 CRUD Operation With Ajax Example – onlinecode

In this post we will give you information about Laravel 7 CRUD Operation With Ajax Example – onlinecode. Hear we will give you detail about Laravel 7 CRUD Operation With Ajax Example – onlinecodeAnd how to use it also give you demo for it if it is necessary.

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 7 crud tutorial with ajax example. it was released on March 3rd, 2020.

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

Overview

Step 1: Install Laravel 7

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 7: Run Our Laravel Application

Step 1 : Install Laravel 7

We are going to install laravel 7, 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.

PHP
composer create-project --prefer-dist laravel/laravel laravel7_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.

PHP
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name(laravel7_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
<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
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
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
<?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
php artisan make:controller StudentController --resource --model=Student

Student.php

PHP
<?php

namespace App;

use IlluminateDatabaseEloquentModel;

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

StudentController.php

PHP
<?php

namespace AppHttpControllers;

use AppStudent;
use IlluminateHttpRequest;
use Response;
class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    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 IlluminateHttpResponse
     */
    public function create()
    {
        //
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    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  AppStudent  $student
     * @return IlluminateHttpResponse
     */
    public function show(Student $student)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  AppStudent  $student
     * @return IlluminateHttpResponse
     */
    public function edit($id)
    {
        //
		$where = array('id' => $id);
        $student  = Student::where($where)->first();
 
        return Response::json($student);
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  AppStudent  $student
     * @return IlluminateHttpResponse
     */
    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  AppStudent  $student
     * @return IlluminateHttpResponse
     */
    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

PHP
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Laravel 7 Ajax CRUD 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 >
    @yield('content')
</div>
</body>
</html>

list.blade.php

PHP
@extends('layouts.app')
@section('content')
    <div >
        <div >
                <h2>Laravel 7 Ajax CRUD Example</h2>
        </div>
        <div >
            <a  href="#" data-toggle="modal" data-target="#addModal">Add</a>
        </div>
    </div>
    @if ($message = Session::get('success'))
        <div >
            {{ $message }}</p>
        </div>
    @endif
    <table  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 }}" >Edit</a>
		     <a data-id="{{ $student->id }}" >Delete</button>
                </td>
            </tr>
        @endforeach
		</tbody>
    </table>
	

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

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

    <!-- Student Modal content-->
    <div >
      <div >
        <button type="button"  data-dismiss="modal">&times;</button>
        <h4 >Update Student</h4>
      </div>
	  <div >
		<form id="updateStudent" name="updateStudent" action="{{ route('student.update') }}" method="post">
			<input type="hidden" name="hdnStudentId" id="hdnStudentId"/>
			@csrf
			<div >
				<label for="txtFirstName">First Name:</label>
				<input type="text"  id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
			</div>
			<div >
				<label for="txtLastName">Last Name:</label>
				<input type="text"  id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
			</div>
			<div >
				<label for="txtAddress">Address:</label>
				<pre  id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></pre>
			</div>
			<button type="submit" >Submit</button>
		</form>
	  </div>
      <div >
        <button type="button"  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 + '" >Edit</a>&nbsp;&nbsp;<a data-id="' + data.id + '" >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 + '" >Edit</a>&nbsp;&nbsp;<a data-id="' + data.id + '" >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

Step 7: Run Our Laravel ApplicationWe 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

Download

Read AlsoLaravel 6 CRUD (Create Read Update Delete) Tutorial For Beginners

Laravel 6 CRUD Operation With Ajax Example

Laravel 6 Pagination Example Tutorial

Laravel 7 Pagination Example Tutorial

Please follow and like us:

Hope this code and post will helped you for implement Laravel 7 CRUD Operation With Ajax Example – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  18  =  24

We accept paid advance and paid guest Posting on our Site : Contact US