Laravel 6 CRUD Operation With Ajax Example
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 crud tutorial with ajax example. it was released on Sept 03, 2019.
Now, we follow the below step for creating the Laravel 6 CRUD Operation With Ajax Example.
laravel 6 crud tutorial, laravel 6 crud example, Laravel 6 CRUD (Create Read Update Delete) Operation For Beginners With Example, CRUD Operations Laravel 6, Laravel 6 CRUD Operation with Example, laravel 6 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
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
We are going to install laravel 6, 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.
1 | composer create-project --prefer-dist laravel/laravel laravel6_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.
1 2 3 4 5 6 | DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=Enter_Your_Database_Name(laravel6_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.
1 | php artisan make:migration create_students_table --create=students |
After complete migration. we need below changes in the database/migrations/create_students_table file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?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.
1 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?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.
1 | php artisan make:controller StudentController --resource --model=Student |
Student.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model { // protected $fillable = [ 'first_name','last_name', 'address' ]; } ?> |
StudentController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | <?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | @extends('layouts.app') @section('content') <div class="row"> <div class="col-lg-11"> <h2>Laravel 6 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">×</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">×</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> <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> <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.
1 | php artisan serve |
Now we will run our example using the below Url in the browser.
1 | http://127.0.0.1:8000/student |