Source Code
Step by step AJAX Crud example in Laravel 5.5
Create Laravel Project (Ajax Crud)
composer create-project --prefer-dist laravel/laravel ajaxcrud
Create new Migration
php artisan make:migration create_posts_table
Post Migration
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->timestamps();
});
Create new Model and new Controller
php artisan make:model Post
php artisan make:controller PostController --resource
Post Model
protected $table = 'posts';
protected $fillable = ['title','description'];
Post Controller
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppPost;
use IlluminateSupportFacadesValidator;
class PostController extends Controller
{
public function index(Request $request)
{
$request->session()->put('search', $request
->has('search') ? $request->get('search') : ($request->session()
->has('search') ? $request->session()->get('search') : ''));
$request->session()->put('field', $request
->has('field') ? $request->get('field') : ($request->session()
->has('field') ? $request->session()->get('field') : 'title'));
$request->session()->put('sort', $request
->has('sort') ? $request->get('sort') : ($request->session()
->has('sort') ? $request->session()->get('sort') : 'asc'));
$posts = new Post();
$posts = $posts->where('title', 'like', '%' . $request->session()->get('search') . '%')
->orderBy($request->session()->get('field'), $request->session()->get('sort'))
->paginate(5);
if ($request->ajax()) {
return view('posts.index', compact('posts'));
} else {
return view('posts.ajax', compact('posts'));
}
}
public function create(Request $request)
{
if ($request->isMethod('get'))
return view('posts.form');
$rules = [
'title' => 'required',
'description' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails())
return response()->json([
'fail' =>true,
'errors' => $validator->errors()
]);
$post = new Post();
$post->title = $request->title;
$post->description = $request->description;
$post->save();
return response()->json([
'fail' => false,
'redirect_url' => url('posts')
]);
}
public function show(Request $request, $id)
{
if($request->isMethod('get')) {
return view('posts.detail',['post' => Post::find($id)]);
}
}
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('posts.form',['post' => Post::find($id)]);
$rules = [
'title' => 'required',
'description' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails())
return response()->json([
'fail' =>true,
'errors' => $validator->errors()
]);
$post = Post::find($id);
$post->title = $request->title;
$post->description = $request->description;
$post->save();
return response()->json([
'fail' => false,
'redirect_url' => url('posts')
]);
}
public function destroy($id)
{
Post::destroy($id);
return redirect('posts');
}
}
Routes
Route::group(['prefix' => 'posts'], function() {
Route::get('/', 'PostController@index');
Route::match(['get', 'post'], 'create', 'PostController@create');
Route::match(['get', 'put'], 'update/{id}', 'PostController@update');
Route::get('show/{id}', 'PostController@show');
Route::delete('delete/{id}', 'PostController@destroy');
});
Views
in the Resources\Views folder, create new folder named with "posts", and in the posts folder create more file like this :
- master.blade.php
- index.blade.php
- ajax.blade.php
- detail.blade.php
- form.blade.php
Master.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Ajax Example</title>
@yield('head')
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
@yield('css')
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar fixed-top bg-info">
<a class="navbar-brand" href="/posts">Laravel Video Tutorial</a>
@yield('nav')
</nav>
@yield('content')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
@yield('js')
</body>
</html>
Index.blade.php
<div class="container">
<div class="row">
<div class="col-sm-7">
<h3>Laravel CRUD, Search, Sort - AJAX</h3>
</div>
<div class="col-sm-5">
<div class="pull-right">
<div class="input-group">
<input class="form-control" id="search"
value="{{ request()->session()->get('search') }}"
onkeydown="if (event.keyCode == 13) ajaxLoad('{{url('posts')}}?search='+this.value)"
placeholder="Search Title" name="search"
type="text" id="search"/>
<div class="input-group-btn">
<button type="submit" class="btn btn-primary"
onclick="ajaxLoad('{{url('posts')}}?search='+$('#search').val())">
<i class="fa fa-search" aria-hidden="true"></i>
</button>
</div>
</div>
</div>
</div>
</div>
<table class="table">
<thead>
<tr>
<th width="60px">No</th>
<th><a href="javascript:ajaxLoad('{{url('posts?field=title&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">Post Title</a>
{{request()->session()->get('field')=='title'?(request()->session()->get('sort')=='asc'?'▴':'▾'):''}}
</th>
<th style="vertical-align: middle">
<a href="javascript:ajaxLoad('{{url('posts?field=description&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">
Description
</a>
{{request()->session()->get('field')=='description'?(request()->session()->get('sort')=='asc'?'▴':'▾'):''}}
</th>
<th style="vertical-align: middle">
<a href="javascript:ajaxLoad('{{url('posts?field=created_at&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">
Created At
</a>
{{request()->session()->get('field')=='created_at'?(request()->session()->get('sort')=='asc'?'▴':'▾'):''}}
</th>
<th style="vertical-align: middle">
<a href="javascript:ajaxLoad('{{url('posts?field=updated_at&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">
Update At
</a>
{{request()->session()->get('field')=='updated_at'?(request()->session()->get('sort')=='asc'?'▴':'▾'):''}}
</th>
<th width="160px" style="vertical-align: middle">
<a href="javascript:ajaxLoad('{{url('posts/create')}}')"
class="btn btn-primary btn-xs"> <i class="fa fa-plus" aria-hidden="true"></i> New Post</a>
</th>
</tr>
</thead>
<tbody>
@php
$i=1;
@endphp
@foreach ($posts as $post)
<tr>
<th>{{$i++}}</th>
<td>{{ $post->title }}</td>
<td >{{ $post->description }}</td>
<td>{{ $post->created_at }}</td>
<td>{{ $post->updated_at }}</td>
<td>
<a class="btn btn-info btn-xs" title="Show"
href="javascript:ajaxLoad('{{url('posts/show/'.$post->id)}}')">
Show</a>
<a class="btn btn-warning btn-xs" title="Edit"
href="javascript:ajaxLoad('{{url('posts/update/'.$post->id)}}')">
Edit</a>
<input type="hidden" name="_method" value="delete"/>
<a class="btn btn-danger btn-xs" title="Delete"
href="javascript:if(confirm('Are you sure want to delete?')) ajaxDelete('{{url('posts/delete/'.$post->id)}}','{{csrf_token()}}')">
Delete
</a>
</td>
</tr>
@endforeach
</tbody>
</table>
<ul class="pagination">
{{ $posts->links() }}
</ul>
</div>
Form.blade.php
<div class="container">
<div class="col-md-8 offset-md-2">
<h1>{{isset($post)?'Edit':'New'}} Post</h1>
<hr/>
@if(isset($post))
{!! Form::model($post,['method'=>'put','id'=>'frm']) !!}
@else
{!! Form::open(['id'=>'frm']) !!}
@endif
<div class="form-group row required">
{!! Form::label("title","Title",["class"=>"col-form-label col-md-3 col-lg-2"]) !!}
<div class="col-md-8">
{!! Form::text("title",null,["class"=>"form-control".($errors->has('title')?" is-invalid":""),"autofocus",'placeholder'=>'Title']) !!}
<span id="error-title" class="invalid-feedback"></span>
</div>
</div>
<div class="form-group row required">
{!! Form::label("description","Description",["class"=>"col-form-label col-md-3 col-lg-2"]) !!}
<div class="col-md-8">
{!! Form::textarea("description",null,["class"=>"form-control".($errors->has('description')?" is-invalid":""),'placeholder'=>'Description']) !!}
<span id="error-description" class="invalid-feedback"></span>
</div>
</div>
<div class="form-group row">
<div class="col-md-3 col-lg-2"></div>
<div class="col-md-4">
<a href="javascript:ajaxLoad('{{url('posts')}}')" class="btn btn-danger btn-xs">
Back</a>
{!! Form::button("Save",["type" => "submit","class"=>"btn btn-primary btn-xs"])!!}
</div>
</div>
{!! Form::close() !!}
</div>
</div>
Detail.blade.php
<div class="container">
<div class="col-md-8 offset-md2">
<h2>Show Post</h2>
<hr>
<div class="form-group">
<h2>{{ $post->title }}</h2>
</div>
<div class="form-group">
<h2>{{ $post->description }}</h2>
</div>
<a class="btn btn-xs btn-danger" href="javascript:ajaxLoad('{{ url('posts') }}')">Back</a>
</div>
</div>
Ajax.blade.php
@extends('posts.master')
@section('css')
<style>
.loading {
background: lightgrey;
padding: 15px;
position: fixed;
border-radius: 4px;
left: 50%;
top: 50%;
text-align: center;
margin: -40px 0 0 -50px;
z-index: 2000;
display: none;
}
.form-group.required label:after {
content: " *";
color: red;
font-weight: bold;
}
</style>
@endsection
@section('content')
<div id="content">
@include('posts.index')
</div>
<div class="loading">
<i class="fa fa-refresh fa-spin fa-2x fa-tw"></i>
<br>
<span>Loading</span>
</div>
@endsection
@section('js')
<script src="{{ asset('js/ajaxcrud.js') }}"></script>
@endsection
Create new Js File
in the Public\js create new file and named it with "ajaxcrud.js"
$(document).on('click', 'a.page-link', function (event) {
event.preventDefault();
ajaxLoad($(this).attr('href'));
});
$(document).on('submit', 'form#frm', function (event) {
event.preventDefault();
var form = $(this);
var data = new FormData($(this)[0]);
var url = form.attr("action");
$.ajax({
type: form.attr('method'),
url: url,
data: data,
cache: false,
contentType: false,
processData: false,
success: function (data) {
$('.is-invalid').removeClass('is-invalid');
if (data.fail) {
for (control in data.errors) {
$('#' + control).addClass('is-invalid');
$('#error-' + control).html(data.errors[control]);
}
} else {
ajaxLoad(data.redirect_url);
}
},
error: function (xhr, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
return false;
});
function ajaxLoad(filename, content) {
content = typeof content !== 'undefined' ? content : 'content';
$('.loading').show();
$.ajax({
type: "GET",
url: filename,
contentType: false,
success: function (data) {
$("#" + content).html(data);
$('.loading').hide();
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
}
function ajaxDelete(filename, token, content) {
content = typeof content !== 'undefined' ? content : 'content';
$('.loading').show();
$.ajax({
type: 'POST',
data: {_method: 'DELETE', _token: token},
url: filename,
success: function (data) {
$("#" + content).html(data);
$('.loading').hide();
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
}
hi when i open in browser min( 14:30 ) i get an error : 'get function in web.php is undefinded'
RépondreSupprimer