🚀 DevOps & SRE Certification Program 📅 Starting: 1st of Every Month 🤝 +91 8409492687 🔍 Contact@DevOpsSchool.com

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Simple Ajax CRUD Application in Laravel

Step 1 – Create a fresh laravel projet

First off all , create a project using following command given below –

$ composer create-project --prefer-dist laravel/laravel AjaxCrud "5.8.*"

Change Directory to AjaxCrud folder

$ cd AjaxCrud

Step 2 – Configure Database in .env file

Step 3 – Open Xampp tool and start the server

Go to phpMyAdmin and create database with same name as .env database name

Step 4 – Set default string length

Locate the file “app/Providers/AppServiceProvider.php” and add following line of code to the top of the file.

use Illuminate\Support\Facades\Schema;

add inside the boot method set a default string length as given below –

Schema::defaultStringLength(191);

Step 5 – Create Database table and Migrate

Now, we have to define table schema for posts table. Open terminal and let’s run the following command to generate a migration file to create posts table in our database

$ php artisan make:migration create_posts_table --create=posts

Step 6 – Open Migration file and put the following code in it

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

Run Migration Command

$ php artisan migrate

Step 7 – Create Model and Some Code

$ php artisan make:model Post

Inside Model, we are adding some code

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'body'];
}
view raw Post.php hosted with ❤ by GitHub

Step 8 – Create Controller Using Command

php artisan make:controller ajaxcrud/AjaxPostController

Inside AjaxPostController, we are adding following code given below –

<?php
namespace App\Http\Controllers\ajaxcrud;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Post;
use Redirect,Response;
class AjaxPostController extends Controller
{
public function index()
{
//
$data['posts'] = Post::orderBy('id','desc')->paginate(8);
return view('ajaxcrud.index',$data);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$postID = $request->post_id;
$post = Post::updateOrCreate(['id' => $postID],
['title' => $request->title, 'body' => $request->body]);
return Response::json($post);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
$where = array('id' => $id);
$post = Post::where($where)->first();
return Response::json($post);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
$post = Post::where('id',$id)->delete();
return Response::json($post);
}
}

Step 9 – Create Blade File/View File

Let’s Create a blade file “index.blade.php” in the “resources/views/ajaxcrud/” directory and put the following code in it respectively

<!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() }}">
<title>Laravel 5.8 Ajax CRUD Application -
DevOpsSchool.com </title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<style>
.container{
padding: 0.5%;
}
</style>
</head>
<body>
<div class="container">
<h2 style="margin-top: 12px;" class="alert alert-success">Laravel 5.8 Ajax CRUD Application - DevOpsSchool.com </h2><br>
<div class="row">
<div class="col-12">
<a href="javascript:void(0)" class="btn btn-success mb-2" id="create-new-post">Add post</a>
<table class="table table-bordered" id="laravel_crud">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<td colspan="2">Action</td>
</tr>
</thead>
<tbody id="posts-crud">
@foreach($posts as $post)
<tr id="post_id_{{ $post->id }}">
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->body }}</td>
<td><a href="javascript:void(0)" id="edit-post" data-id="{{ $post->id }}" class="btn btn-info">Edit</a></td>
<td>
<a href="javascript:void(0)" id="delete-post" data-id="{{ $post->id }}" class="btn btn-danger delete-post">Delete</a></td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
<div class="modal fade" id="ajax-crud-modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="postCrudModal"></h4>
</div>
<div class="modal-body">
<form id="postForm" name="postForm" class="form-horizontal">
<input type="hidden" name="post_id" id="post_id">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Title</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="title" name="title" value="" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Body</label>
<div class="col-sm-12">
<input class="form-control" id="body" name="body" value="" required="">
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btn-save" value="create">Save
</button>
</div>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#create-new-post').click(function () {
$('#btn-save').val("create-post");
$('#postForm').trigger("reset");
$('#postCrudModal').html("Add New post");
$('#ajax-crud-modal').modal('show');
});
$('body').on('click', '#edit-post', function () {
var post_id = $(this).data('id');
$.get('ajax-posts/'+post_id+'/edit', function (data) {
$('#postCrudModal').html("Edit post");
$('#btn-save').val("edit-post");
$('#ajax-crud-modal').modal('show');
$('#post_id').val(data.id);
$('#title').val(data.title);
$('#body').val(data.body);
})
});
$('body').on('click', '.delete-post', function () {
var post_id = $(this).data("id");
confirm("Are You sure want to delete !");
$.ajax({
type: "DELETE",
url: "{{ url('ajax-posts')}}"+'/'+post_id,
success: function (data) {
$("#post_id_" + post_id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
if ($("#postForm").length > 0) {
$("#postForm").validate({
submitHandler: function(form) {
var actionType = $('#btn-save').val();
$('#btn-save').html('Sending..');
$.ajax({
data: $('#postForm').serialize(),
url: "{{ route('ajax-posts.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
var post = '<tr id="post_id_' + data.id + '"><td>' + data.id + '</td><td>' + data.title + '</td><td>' + data.body + '</td>';
post += '<td><a href="javascript:void(0)" id="edit-post" data-id="' + data.id + '" class="btn btn-info">Edit</a></td>';
post += '<td><a href="javascript:void(0)" id="delete-post" data-id="' + data.id + '" class="btn btn-danger delete-post">Delete</a></td></tr>';
if (actionType == "create-post") {
$('#posts-crud').prepend(post);
} else {
$("#post_id_" + data.id).replaceWith(post);
}
$('#postForm').trigger("reset");
$('#ajax-crud-modal').modal('hide');
$('#btn-save').html('Save Changes');
},
error: function (data) {
console.log('Error:', data);
$('#btn-save').html('Save Changes');
}
});
}
})
}
</script>

Step 10 – Create Resource Routes

We need to add a resource route in “routes/web.php”. Let’s open “routes/web.php” file and add the following route.

Route::resource('ajax-posts', 'ajaxcrud\AjaxPostController');

Start The Development Server

$ php artisan serve

Output

Add Post

Edit, we are editing and updating the data

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.