Ajax CRUD example in Laravel 5.5 application

September 3, 2017 | Category : Laravel 5.5 Laravel 5 Ajax JQuery Plugin JQuery Bootstrap Laravel PHP

Hello Friends,

Few days ago i posted simple crud application in laravel 5 application as here CRUD Laravel 5 Application, But in this article we will learn insert update delete and view jquery ajax crud example in laravel 5.5 application.

We love always like to simple and speed of our web application. If you are using ajax then all operation become fast and really smooth. If you are using ajax then your app become fast and no more load. So if you would like to use jquery ajax in your application then you can do it simple step.

we will learn ajax basic crud example, here we will create "posts" table and we will do it using ajax. In this article we will create migration, model, controller, view and js file. So using those things we will make basic jquery ajax example. you have to just follow few step:

1) Install Laravel 5.5 Using Command

2) Database configuration in .env file

3) Create posts table migration

4) Create posts model

5) Create routes

6) Create PostController

7) Create my-posts.blade.php file

8) Create posts-ajax.js file

After you will get bellow preview of ajax crud application:

Preview:

Step 1 - Install Laravel 5.5 Using Command

composer create-project --prefer-dist laravel/laravel blog

Step 2 - Database configuration in .env file

.env

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=here your database name(blog)

DB_USERNAME=here database username(root)

DB_PASSWORD=here database password(root)

Step 3 - Create posts table migration

php artisan make:migration create_posts_table

database/migrations/create_posts_table.php

<?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->increments('id');

$table->string('title');

$table->text('details');

$table->timestamps();

});

}


/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('posts');

}

}

Run migration by following command:

php artisan migrate

Step 4 - Create posts model

php artisan make:demo Post

app/Post.php

<?php


namespace App;


use Illuminate\Database\Eloquent\Model;


class Post extends Model

{

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'title', 'details'

];

}

Step 5 - Create routes

routes/web.php

Route::get('my-posts', 'PostController@myPosts');

Route::resource('posts','PostController');

Step 6 - Create PostController

app/Http/Controllers/PostController.php

<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use App\Post;


class PostController extends Controller

{


/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function myPosts()

{

return view('my-posts');

}


/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$posts = Post::latest()->paginate(5);

return response()->json($posts);

}


/**

* Store a newly created resource in storage.

*

* @param \Illuminate\Http\Request $request

* @return \Illuminate\Http\Response

*/

public function store(Request $request)

{

$post = Post::create($request->all());

return response()->json($post);

}


/**

* Update the specified resource in storage.

*

* @param \Illuminate\Http\Request $request

* @param int $id

* @return \Illuminate\Http\Response

*/

public function update(Request $request, $id)

{

$post = Post::find($id)->update($request->all());

return response()->json($post);

}


/**

* Remove the specified resource from storage.

*

* @param int $id

* @return \Illuminate\Http\Response

*/

public function destroy($id)

{

Post::find($id)->delete();

return response()->json(['done']);

}

}

Step 7 - Create my-posts.blade.php file

resources/views/my-posts.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Laravel 5.5 Ajax CRUD Example</title>

<meta name="csrf-token" content="{{ csrf_token() }}">

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css">

</head>

<body>

<div class="container">

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>Laravel 5.5 Ajax CRUD Example</h2>

</div>

<div class="pull-right">

<button type="button" class="btn btn-success" data-toggle="modal" data-target="#create-item">Create Post</button>

</div>

</div>

</div>

<table class="table table-bordered">

<thead>

<tr>

<th>Title</th>

<th>Details</th>

<th width="200px">Action</th>

</tr>

</thead>

<tbody>

</tbody>

</table>


<ul id="pagination" class="pagination-sm"></ul>


<!-- Create Item Modal -->

@include('create')

<!-- Edit Item Modal -->

@include('edit')


</div>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.min.js"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twbs-pagination/1.3.1/jquery.twbsPagination.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.min.js"></script>

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>

<link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet">


<script type="text/javascript">

var url = "<?php echo route('posts.index')?>";

</script>

<script src="/js/posts-ajax.js"></script>


</body>

</html>

resources/views/create.blade.php

<div class="modal fade" id="create-item" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

<div class="modal-dialog" role="document">

<div class="modal-content">

<div class="modal-header">

<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>

<h4 class="modal-title" id="myModalLabel">Create Item</h4>

</div>

<div class="modal-body">

<form data-toggle="validator" action="{{ route('posts.store') }}" method="POST">

<div class="form-group">

<label class="control-label" for="title">Title:</label>

<input type="text" name="title" class="form-control" data-error="Please enter title." required />

<div class="help-block with-errors"></div>

</div>

<div class="form-group">

<label class="control-label" for="title">Description:</label>

<textarea name="details" class="form-control" data-error="Please enter details." required></textarea>

<div class="help-block with-errors"></div>

</div>

<div class="form-group">

<button type="submit" class="btn crud-submit btn-success">Submit</button>

</div>

</form>

</div>

</div>

</div>

</div>

resources/views/edit.blade.php

<div class="modal fade" id="edit-item" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

<div class="modal-dialog" role="document">

<div class="modal-content">

<div class="modal-header">

<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>

<h4 class="modal-title" id="myModalLabel">Edit Item</h4>

</div>

<div class="modal-body">

<form data-toggle="validator" action="/item-ajax/14" method="put">

<div class="form-group">

<label class="control-label" for="title">Title:</label>

<input type="text" name="title" class="form-control" data-error="Please enter title." required />

<div class="help-block with-errors"></div>

</div>

<div class="form-group">

<label class="control-label" for="title">Description:</label>

<textarea name="details" class="form-control" data-error="Please enter details." required></textarea>

<div class="help-block with-errors"></div>

</div>

<div class="form-group">

<button type="submit" class="btn btn-success crud-submit-edit">Submit</button>

</div>

</form>

</div>

</div>

</div>

</div>

Step 8 - Create posts-ajax.js file

public/js/posts-ajax.js

var page = 1;

var current_page = 1;

var total_page = 0;

var is_ajax_fire = 0;


manageData();


/* manage data list */

function manageData() {

$.ajax({

dataType: 'json',

url: url,

data: {page:page}

}).done(function(data){

total_page = data.last_page;

current_page = data.current_page;

$('#pagination').twbsPagination({

totalPages: total_page,

visiblePages: current_page,

onPageClick: function (event, pageL) {

page = pageL;

if(is_ajax_fire != 0){

getPageData();

}

}

});

manageRow(data.data);

is_ajax_fire = 1;

});

}


$.ajaxSetup({

headers: {

'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

}

});


/* Get Page Data*/

function getPageData() {

$.ajax({

dataType: 'json',

url: url,

data: {page:page}

}).done(function(data){

manageRow(data.data);

});

}


/* Add new Post table row */

function manageRow(data) {

var rows = '';

$.each( data, function( key, value ) {

rows = rows + '<tr>';

rows = rows + '<td>'+value.title+'</td>';

rows = rows + '<td>'+value.details+'</td>';

rows = rows + '<td data-id="'+value.id+'">';

rows = rows + '<button data-toggle="modal" data-target="#edit-item" class="btn btn-primary edit-item">Edit</button> ';

rows = rows + '<button class="btn btn-danger remove-item">Delete</button>';

rows = rows + '</td>';

rows = rows + '</tr>';

});

$("tbody").html(rows);

}


/* Create new Post */

$(".crud-submit").click(function(e){

e.preventDefault();

var form_action = $("#create-item").find("form").attr("action");

var title = $("#create-item").find("input[name='title']").val();

var details = $("#create-item").find("textarea[name='details']").val();

$.ajax({

dataType: 'json',

type:'POST',

url: form_action,

data:{title:title, details:details}

}).done(function(data){

getPageData();

$(".modal").modal('hide');

toastr.success('Post Created Successfully.', 'Success Alert', {timeOut: 5000});

});

});


/* Remove Post */

$("body").on("click",".remove-item",function(){

var id = $(this).parent("td").data('id');

var c_obj = $(this).parents("tr");

$.ajax({

dataType: 'json',

type:'delete',

url: url + '/' + id,

}).done(function(data){

c_obj.remove();

toastr.success('Post Deleted Successfully.', 'Success Alert', {timeOut: 5000});

getPageData();

});

});


/* Edit Post */

$("body").on("click",".edit-item",function(){

var id = $(this).parent("td").data('id');

var title = $(this).parent("td").prev("td").prev("td").text();

var details = $(this).parent("td").prev("td").text();

$("#edit-item").find("input[name='title']").val(title);

$("#edit-item").find("textarea[name='details']").val(details);

$("#edit-item").find("form").attr("action",url + '/' + id);

});


/* Updated new Post */

$(".crud-submit-edit").click(function(e){

e.preventDefault();

var form_action = $("#edit-item").find("form").attr("action");

var title = $("#edit-item").find("input[name='title']").val();

var details = $("#edit-item").find("textarea[name='details']").val();

$.ajax({

dataType: 'json',

type:'PUT',

url: form_action,

data:{title:title, details:details}

}).done(function(data){

getPageData();

$(".modal").modal('hide');

toastr.success('Post Updated Successfully.', 'Success Alert', {timeOut: 5000});

});

});

now you are ready to run your application using query run.

I hope you found your best solution.