Ajax CRUD with Laravel 8 tutorial will explain you how to create ajax crud with laravel 8 tutorial with example (Create, Read, Update, Delete) Step by step for beginners. Here we will show you laravel ajax crud operation with showing validations errors, search sort and pagination and bootstrap modal popup for create and edit the data without page refresh or reload.
Laravel is a well-architectured framework that’s easy to pick up and write elegant code, but it’s powerful as well. It contains many advanced features out-of-the-box: Eloquent ORM, support for unit/feature/browser tests, job queues, and many more.
There’s an abundance of great learning resources and it boasts one of the largest communities on the net, so it’s easy to find developers who are familiar with it. Today, I’m going to show you crud with Laravel with ajax jquery.
1. Install Laravel App
First at all install a new laravel app using running the below command.
composer create-project --prefer-dist laravel/laravel laravelajax
Go into the app
cd laravelajax
2. Configure .env file
Next open the .env file and enter your database credentials such as database_name, username, password:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ajax_crud
DB_USERNAME=root
DB_PASSWORD=
3. Create Model and Run Migration
Next generate a model and migration using the below command.
php artisan make:model Post -m
After running this command you will get one model file Post.php and one migration file.
Navigate the database/migrations directory and open the database\migrations\2021_03_21_061250_create_posts_table.php file and update your database tables on it;
<?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')->nullable();
$table->longText('description')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
After this run the below command
php artisan migrate
Next, open your app\Models\Post.php file and update Fillable Properties on it just like below;
<?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'
];
}
4. Update Route
Next, open your routes/web.php file and update the laravel 8 crud with ajax routes same like below.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
Route::resource('posts', PostController::class);
Route::get('/', function () {
return view('welcome');
});
5. Create Controller
Next, you need to create new controller named as PostController using running below command.
php artisan make:controller PostController --resource
After successfully created controller, open app/Http/Controllers/PostController.php file and update the methods on it;
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::all();
return view('posts', ['posts' => $posts]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'title' => 'required|max:255',
'description' => 'required',
]);
$post = Post::updateOrCreate(['id' => $request->id], [
'title' => $request->title,
'description' => $request->description
]);
return response()->json(['code'=>200, 'message'=>'Post Created successfully','data' => $post], 200);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$post = Post::find($id);
return response()->json($post);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post = Post::find($id)->delete();
return response()->json(['success'=>'Post Deleted successfully']);
}
}
6. Create Blade File
In this step, navigate the rosources/views directory and open the resources\views\posts.blade.php file and put the below code on it;
<!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() }}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/r/bs-3.3.5/jq-2.1.4,dt-1.10.8/datatables.min.css"/>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/r/bs-3.3.5/jqc-1.11.3,dt-1.10.8/datatables.min.js"></script>
</head>
<style>
.alert-message {
color: red;
}
</style>
<body>
<div class="container">
<h2 style="margin-top: 12px;" class="alert alert-success">Ajax CRUD with Laravel App -
<a href="https://www.codingdriver.com" target="_blank" >CodingDriver</a>
</h2><br>
<div class="row">
<div class="col-12 text-right">
<a href="javascript:void(0)" class="btn btn-success mb-3" id="create-new-post" onclick="addPost()">Add Post</a>
</div>
</div>
<div class="row" style="clear: both;margin-top: 18px;">
<div class="col-12">
<table id="laravel_crud" class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
@foreach($posts as $post)
<tr id="row_{{$post->id}}">
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->description }}</td>
<td><a href="javascript:void(0)" data-id="{{ $post->id }}" onclick="editPost(event.target)" class="btn btn-info">Edit</a></td>
<td>
<a href="javascript:void(0)" data-id="{{ $post->id }}" class="btn btn-danger" onclick="deletePost(event.target)">Delete</a></td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
7. Add Model
After adding the posts blade file now add a model after last closing div. If you have any issue you can ask below command.
<div class="modal fade" id="post-modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<form name="userForm" class="form-horizontal">
<input type="hidden" name="post_id" id="post_id">
<div class="form-group">
<label for="name" class="col-sm-2">title</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="title" name="title" placeholder="Enter title">
<span id="titleError" class="alert-message"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2">Description</label>
<div class="col-sm-12">
<textarea class="form-control" id="description" name="description" placeholder="Enter description" rows="4" cols="50">
</textarea>
<span id="descriptionError" class="alert-message"></span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="createPost()">Save</button>
</div>
</div>
</div>
</div>
8. Add JS & Ajax Request
Now add jquery and ajax code after closing in body tag for laravel 8 ajax crud.
<script>
$('#laravel_crud').DataTable();
function addPost() {
$("#post_id").val('');
$('#post-modal').modal('show');
}
function editPost(event) {
var id = $(event).data("id");
let _url = `/posts/${id}`;
$('#titleError').text('');
$('#descriptionError').text('');
$.ajax({
url: _url,
type: "GET",
success: function(response) {
if(response) {
$("#post_id").val(response.id);
$("#title").val(response.title);
$("#description").val(response.description);
$('#post-modal').modal('show');
}
}
});
}
function createPost() {
var title = $('#title').val();
var description = $('#description').val();
var id = $('#post_id').val();
let _url = `/posts`;
let _token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: _url,
type: "POST",
data: {
id: id,
title: title,
description: description,
_token: _token
},
success: function(response) {
if(response.code == 200) {
if(id != ""){
$("#row_"+id+" td:nth-child(2)").html(response.data.title);
$("#row_"+id+" td:nth-child(3)").html(response.data.description);
} else {
$('table tbody').prepend('<tr id="row_'+response.data.id+'"><td>'+response.data.id+'</td><td>'+response.data.title+'</td><td>'+response.data.description+'</td><td><a href="javascript:void(0)" data-id="'+response.data.id+'" onclick="editPost(event.target)" class="btn btn-info">Edit</a></td><td><a href="javascript:void(0)" data-id="'+response.data.id+'" class="btn btn-danger" onclick="deletePost(event.target)">Delete</a></td></tr>');
}
$('#title').val('');
$('#description').val('');
$('#post-modal').modal('hide');
}
},
error: function(response) {
$('#titleError').text(response.responseJSON.errors.title);
$('#descriptionError').text(response.responseJSON.errors.description);
}
});
}
function deletePost(event) {
var id = $(event).data("id");
let _url = `/posts/${id}`;
let _token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: _url,
type: 'DELETE',
data: {
_token: _token
},
success: function(response) {
$("#row_"+id).remove();
}
});
}
</script>
You May also Like:
Laravel 8 CRUD Example | Laravel 8 Tutorial For Beginners
So, guys the Laravel 8 AJAX CRUD Example Tutorial from Scratch is over now. If you have any issues or query about ajax crud with laravel please comment us. Follow us on twitter for more update’s.
Hi Rasool, Code is correct and its working fine, let me know which type issue you are getting.
Hi Rasool, Code is correct and its working fine, let me know which type issue you are getting.
Thanks for your good site. The problem was solved
Add a good tutorial on using Ajax in your shopping cart.
Another suggestion is to introduce and how to use the packages. Please put a section to introduce them and give good examples of their use.
Thank you for your hard work