We can use Ajax in Laravel 8 for creating any application. Ajax will make an asynchronous execution of the webpage. So, if you want to create a webpage in PHP. And you don’t want to reload it, you will have to use the Ajax. In this post, I will show you how to create a Laravel 8 Ajax CRUD application. I have already shared a post for the Laravel 8 CRUD application. But, in that project, the webpage is reloading on the form submit. That’s why, through this post, I will implement it using the Ajax. Hence, let’s create a project and start diving into it.
Prerequisites
For creating a new project in Laravel 8 for ajax crud, your system must required the following tools.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
Create Project For Laravel 8 Ajax CRUD
We will use composer to create the project. So, in the terminal or command prompt hit the belwo command.
composer create-project --prefer-dist laravel/laravel ajax-crud
This will take a couple of minutes for creating this project.
After completing the installation of the above project, let’s create and configure the database.
Laravel 8 Multiple Images Upload with Validation
Create and Configure Database
For the database, I will be using the MySQL. So, just create a database by giving the name there.
CREATE DATABASE ajax_crud;
Now, we have the database ready. Therefore, let’s configure it for the project. This will establish a database connection.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ajax_crud
DB_USERNAME=root
DB_PASSWORD=root
After configuring the database, let’s create a model and migration.
Create a Model, Migration, and Controller
For implementing the ajax crud operation, it will require the model and migration. Hence, I will be creating these all by a single command. Larvel provides the facility to create the model, migration, and controller in one line of command.
php artisan make:model Post -mcr
The above command will generate these three files.
Once, these files created, firstly open the migration file. You can find it the create_posts_table.php migration file inside the database.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
So, here, I have added the migration file as well. Now, let’s migrate the table.
php artisan migrate
The above command will migrate the tables.
How to Upload Image in Laravel 8 with Validation
Add Fillable Data in Model
For the model, we will have to add the fillable data. So, in the Post.php add the below fillable data as a mass assignment.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
"title", "description"
];
}
So, we have the tables ready and added the mass assignment. Now, let’s move to the functionality for creating the ajax crud application.
In the PostController.php we have the resource for the CRUD operation. Now, we will be putting out the functionalities inside these functions.
Add the below code snippet in the PostController.php file.
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
// ----------- [ post listing ] -------------
public function index()
{
$posts = Post::latest()->paginate(5);
return view('index', compact('posts'));
}
// ------------- [ store post ] -----------------
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
]);
$post = Post::create($request->all());
if(!is_null($post)) {
return response()->json(["status" => "success", "message" => "Success! post created.", "data" => $post]);
}
else {
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
}
}
// ---------------- [ Update post ] -------------
public function update(Request $request)
{
$post_id = $request->id;
$post = Post::where("id", $post_id)->update($request->all());
if($post == 1) {
return response()->json(["status" => "success", "message" => "Success! post updated"]);
}
else {
return response()->json(["status" => "failed", "message" => "Alert! post not updated"]);
}
}
// -------------- [ Delete post ] ---------------
public function destroy($post_id) {
$post = Post::where("id", $post_id)->delete();
if($post == 1) {
return response()->json(["status" => "success", "message" => "Success! post deleted"]);
}
else {
return response()->json(["status" => "failed", "message" => "Alert! post not deleted"]);
}
}
}
After adding the above snippet, we’ll require adding the routes. Here, add these routes in the web.php.
<?php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
Route::get('posts', [PostController::class, 'index']);
Route::post('post', [PostController::class, 'store']);
Route::put('post', [PostController::class, 'update']);
Route::delete('post/{post_id}', [PostController::class, 'destroy']);
Laravel 8 Form Validation Tutorial For Beginners
Create Views For Ajax CRUD Application
Now, the functionality part has been done. So, let’s read and render the data in the view side.
For the Ajax CRUD application, I will be creating the following views –
- master.blade.php
- index.blade.php
I will perform the CRUD operation through the Bootstrap 4 Modal. So, it will not require the views for all the operations.
In the master blade, I will include the bootstrap and js file. Then all the activities will gonna perform from the index blade.
<!doctype html>
<html lang="en">
<head>
<title> @yield('title') | Laravel 8 Ajax CRUD | Programming Fields </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>
<div class="container mt-5">
<h4 class="text-center font-weight-bold"> Laravel 8 Ajax CRUD Application - Programming Fields </h4>
@yield('content')
</div>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="{{asset('js/script.js')}}"></script>
</body>
</html>
After adding the above snippet in the master blade, add the next snippet.
@extends('master')
@section('title') Posts Listing @endsection
@section('content')
<style>
svg.w-5.h-5{
width: 25px !important;
}
span.relative.z-0.inline-flex.shadow-sm.rounded-md{
float: right !important;
}
</style>
<div class="row">
<div class="col-xl-6">
<div id="result"></div>
</div>
<div class="col-xl-6 text-right">
<a href="javascript:void(0);" data-target="#addPostModal" data-toggle="modal" class="btn btn-success"> Add New </a>
</div>
</div>
<table class="table table-striped mt-4">
<thead>
<th> Post Id </th>
<th> Title </th>
<th> Description </th>
<th> Action </th>
</thead>
<tbody>
@foreach ($posts as $post)
<tr>
<td> {{$post->id}} </td>
<td> {{$post->title}} </td>
<td> {{$post->description}} </td>
<td>
<a href="javascript:void(0);" data-toggle="modal" data-target="#addPostModal" data-id="{{$post->id}}" data-title="{{$post->title}}" data-description="{{$post->description}}" data-action="view" class="btn btn-info btn-sm"> View </a>
<a href="javascript:void(0);" data-toggle="modal" data-target="#addPostModal" data-id="{{$post->id}}" data-title="{{$post->title}}" data-description="{{$post->description}}" data-action="edit" class="btn btn-success btn-sm"> Edit </a>
<a href="javascript:void(0);" onclick="deletePost({{$post->id}})" class="btn btn-danger btn-sm"> Delete </a>
</td>
</tr>
@endforeach
</tbody>
</table>
<!-- Create post modal -->
<div class="modal fade" id="addPostModal" tabindex="-1" role="dialog" aria-labelledby="addPostModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addPostModalLabel"> Create Post </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"> × </span>
</button>
</div>
<div class="modal-body">
<form method="POST" id="postForm">
{{-- @csrf --}}
<input type="hidden" id="id_hidden" name="id" />
<div class="form-group">
<label for="title"> Title <span class="text-danger">*</span></label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="title"> Description <span class="text-danger">*</span></label>
<textarea name="description" id="description" class="form-control"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" id="createBtn" class="btn btn-primary"> Save </button>
</div>
<div class="result"></div>
</div>
</div>
</div>
{!! $posts->links() !!}
@endsection
How to Implement Column Filter in Laravel 7 Yajra Datatable
Add Javascript For Laravel 8
For completing the entire events and action, you will have to add some script. So, create a folder named js inside the public folder. Then inside the js folder create a file named script.js At last, add the below script there.
// Pass csrf token in ajax header
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//----- [ button click function ] ----------
$("#createBtn").click(function(event) {
event.preventDefault();
$(".error").remove();
$(".alert").remove();
var title = $("#title").val();
var description = $("#description").val();
if(title == "") {
$("#title").after('<span class="text-danger error"> Title is required </span>');
}
if(description == "") {
$("#description").after('<span class="text-danger error"> Description is required </span>');
return false;
}
var form_data = $("#postForm").serialize();
// if post id exist
if($("#id_hidden").val() !="") {
updatePost(form_data);
}
// else create post
else {
createPost(form_data);
}
});
// create new post
function createPost(form_data) {
$.ajax({
url: 'post',
method: 'post',
data: form_data,
dataType: 'json',
beforeSend:function() {
$("#createBtn").addClass("disabled");
$("#createBtn").text("Processing..");
},
success:function(res) {
$("#createBtn").removeClass("disabled");
$("#createBtn").text("Save");
if(res.status == "success") {
$(".result").html("<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message+ "</div>");
}
else if(res.status == "failed") {
$(".result").html("<div class='alert alert-danger alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message+ "</div>");
}
}
});
}
// update post
function updatePost(form_data) {
$.ajax({
url: 'post',
method: 'put',
data: form_data,
dataType: 'json',
beforeSend:function() {
$("#createBtn").addClass("disabled");
$("#createBtn").text("Processing..");
},
success:function(res) {
$("#createBtn").removeClass("disabled");
$("#createBtn").text("Update");
if(res.status == "success") {
$(".result").html("<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message+ "</div>");
}
else if(res.status == "failed") {
$(".result").html("<div class='alert alert-danger alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message+ "</div>");
}
}
});
}
// ---------- [ Delete post ] ----------------
function deletePost(post_id) {
var status = confirm("Do you want to delete this post?");
if(status == true) {
$.ajax({
url: "post/"+post_id,
method: 'delete',
dataType: 'json',
success:function(res) {
if(res.status == "success") {
$("#result").html("<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message + "</div>");
}
else if(res.status == "failed") {
$("#result").html("<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message + "</div>");
}
}
});
}
}
$('#addPostModal').on('shown.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id');
var title = $(e.relatedTarget).data('title');
var description = $(e.relatedTarget).data('description');
var action = $(e.relatedTarget).data('action');
if(action !== undefined) {
if(action === "view") {
// set modal title
$(".modal-title").html("Post Detail");
// pass data to input fields
$("#title").attr("readonly", "true");
$("#title").val(title);
$("#description").attr("readonly", "true");
$("#description").val(description);
// hide button
$("#createBtn").addClass("d-none");
}
if(action === "edit") {
$("#title").removeAttr("readonly");
$("#description").removeAttr("readonly");
// set modal title
$(".modal-title").html("Update Post");
$("#createBtn").text("Update");
// pass data to input fields
$("#id_hidden").val(id);
$("#title").val(title);
$("#description").val(description);
// hide button
$("#createBtn").removeClass("d-none");
}
}
else {
$(".modal-title").html("Create Post");
// pass data to input fields
$("#title").removeAttr("readonly");
$("#title").val("");
$("#description").removeAttr("readonly");
$("#description").val("");
// hide button
$("#createBtn").removeClass("d-none");
}
});
After adding the above views, we will have to
Save and run the application on the specified endpoint.
Laravel 7 RESTful APIs For Todo App with Passport Auth
Check the Result of Ajax CRUD Application
Firstly, when you will run the application, the index blade will be opened.
Currently, we have not any posts. So, create post by clicking on Add New button. A modal will open with the form.
In this form, I have set the form validation using the jQuery. So, when you will try to create post without filling the detail, it will show you the validation errors.
Enter the post detail and click on the Save button. You will have the success message as showing below.
I have added few posts here. Now, in the action, we have the View, Edit and Delete.
When you will click on the View, the post detail will be passed on the modal form. In the View action, the inputs are in readonly mode. Also, the button is hidden.
Similarly, when you click on the Edit button, it will again open the same modal. But this time, you will have the inputs enabled with the write option, The button is visible as well.
How to Create Auth with Jetstream and Livewire in Laravel 8
Now, update the post and you will have the success message as showing below.
At last, when you will try to delete the post, you will have a confirmation.
When you will confirm the delete then it will delete the post. Also, you will have the success message as showing below.
Laravel 7 Yajra DataTable with Server Side Processing
Conclusion
The Laravel 8 Ajax CRUD application performed on the Bootstrap modal. So, it doesn’t require more views to perform a certain form of actions. Also, it reduces the code snippet that a normal CRUD operations. So, finally, we have implemented the AJAX in Laravel 8.
Huitzitzili says
good tutorial could you make one explaining how to make a log using react js and axios?
Umesh Rana says
But what kind of log tutorial that you are looking for, would you elaborate more?
Pulok Hossain says
Good tutorial.
But there is still a problem. When adding a new row or editing one it doesn’t show the changes immediately !
If i want to see the new changes, i need to reload the page.
can you fix this please, I am new to JavaScript .
Thank You.
Umesh Rana says
You can do it by an Ajax call to fetch the data from the database table. Then bind the data into table td and append it to the table.