Laravel 5.2 and AngularJS CRUD with Search and Pagination Example.

Laravel 5.2 and AngularJS CRUD with Search and Pagination Example.

In this post we will give you information about Laravel 5.2 and AngularJS CRUD with Search and Pagination Example.. Hear we will give you detail about Laravel 5.2 and AngularJS CRUD with Search and Pagination Example.And how to use it also give you demo for it if it is necessary.

Now i show you how to create CRUD(Create, Read, Update, Delete) using AngularJS and Laravel 5. In Following step by step you can create web application of create, edit, delete, lists, search with pagination of items modules. In this post through you can make simple crud, search and pagination module and easily use in your laravel project. I am going to show preview of items module that we will do using angularJS and Laravel 5.2.

Preview

Step 1: Create items table and module

In First step we have to create migration for items table using Laravel 5 php artisan command, so first fire bellow command:

php artisan make:migration create_items_table

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create items table.

use IlluminateDatabaseSchemaBlueprint;

use IlluminateDatabaseMigrationsMigration;

class CreateItemsTable extends Migration

{

public function up()

{

Schema::create('items', function (Blueprint $table) {

$table->increments('id');

$table->string('title');

$table->text('description');

$table->timestamps();

});

}

public function down()

{

Schema::drop("items");

}

}

After craete “items” table you should craete Item model for items, so first create file in this path app/Item.php and put bellow content in item.php file:

app/Item.php

namespace App;

use IlluminateDatabaseEloquentModel;

use DB;

class Item extends Model

{

public $fillable = ['title','description'];

}

Step 2: Create controller

Ok, now we should create new controller as ItemController in this path app/Http/Controllers/ItemController.php. this controller will manage all lists, create, edit, delete ,search and pagination request and return json response, so put bellow content in controller file:

app/Http/Controllers/ItemController.php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppHttpControllersController;

use AppItem;

class ItemController extends Controller

{

public function index(Request $request)

{

$input = $request->all();

if($request->get('search')){

$items = Item::where("title", "LIKE", "%{$request->get('search')}%")

->paginate(5);

}else{

$items = Item::paginate(5);

}

return response($items);

}

public function store(Request $request)

{

$input = $request->all();

$create = Item::create($input);

return response($create);

}

public function edit($id)

{

$item = Item::find($id);

return response($item);

}

public function update(Request $request,$id)

{

$input = $request->all();

Item::where("id",$id)->update($input);

$item = Item::find($id);

return response($item);

}

public function destroy($id)

{

return Item::where('id',$id)->delete();

}

}

Also see:Codeigniter 3 and AngularJS CRUD with Search and Pagination Example.

Step 3: Route file

In this step you have to add some route in your route file. so first we will add resource route for items module and another one for templates route. this templates route through we will get html template for our application, so put the bellow content in route file:

app/Http/routes.php

Route::get('/', function () {

return view('app');

});

Route::group(['middleware' => ['web']], function () {

Route::resource('items', 'ItemController');

});

// Templates

Route::group(array('prefix'=>'/templates/'),function(){

Route::get('{template}', array( function($template)

{

$template = str_replace(".html","",$template);

View::addExtension('html','php');

return View::make('templates.'.$template);

}));

});

Step 4: use AngularJS

Now we will manage AngularJS route and controller, so first cretae “app” directory in your public folder(public/app) and create route.js(public/app/route.js) file for write all angular js. and put the bellow code in that file.

route.js

var app = angular.module('main-App',['ngRoute','angularUtils.directives.dirPagination']);

app.config(['$routeProvider',

function($routeProvider) {

$routeProvider.

when('/', {

templateUrl: 'templates/home.html',

controller: 'AdminController'

}).

when('/items', {

templateUrl: 'templates/items.html',

controller: 'ItemController'

});

}]);

now we have to create one folder in your app folder “controllers” and create one file “ItemController.js”(public/app/controllers/ItemController.js) file in that folder.

ItemController.js

app.controller('AdminController', function($scope,$http){

$scope.pools = [];

});

app.controller('ItemController', function(dataFactory,$scope,$http){

$scope.data = [];

$scope.libraryTemp = {};

$scope.totalItemsTemp = {};

$scope.totalItems = 0;

$scope.pageChanged = function(newPage) {

getResultsPage(newPage);

};

getResultsPage(1);

function getResultsPage(pageNumber) {

if(! $.isEmptyObject($scope.libraryTemp)){

dataFactory.httpRequest('/items?search='+$scope.searchText+'&page='+pageNumber).then(function(data) {

$scope.data = data.data;

$scope.totalItems = data.total;

});

}else{

dataFactory.httpRequest('/items?page='+pageNumber).then(function(data) {

$scope.data = data.data;

$scope.totalItems = data.total;

});

}

}

$scope.searchDB = function(){

if($scope.searchText.length >= 3){

if($.isEmptyObject($scope.libraryTemp)){

$scope.libraryTemp = $scope.data;

$scope.totalItemsTemp = $scope.totalItems;

$scope.data = {};

}

getResultsPage(1);

}else{

if(! $.isEmptyObject($scope.libraryTemp)){

$scope.data = $scope.libraryTemp ;

$scope.totalItems = $scope.totalItemsTemp;

$scope.libraryTemp = {};

}

}

}

$scope.saveAdd = function(){

dataFactory.httpRequest('items','POST',{},$scope.form).then(function(data) {

$scope.data.push(data);

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

});

}

$scope.edit = function(id){

dataFactory.httpRequest('items/'+id+'/edit').then(function(data) {

console.log(data);

$scope.form = data;

});

}

$scope.saveEdit = function(){

dataFactory.httpRequest('items/'+$scope.form.id,'PUT',{},$scope.form).then(function(data) {

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

$scope.data = apiModifyTable($scope.data,data.id,data);

});

}

$scope.remove = function(item,index){

var result = confirm("Are you sure delete this item?");

if (result) {

dataFactory.httpRequest('items/'+item.id,'DELETE').then(function(data) {

$scope.data.splice(index,1);

});

}

}

});

we have to create another folder “helper” in app directory for myHelper.js(public/app/helper/myHelper.js) file because that file will help to define helper function.

myHelper.js

function apiModifyTable(originalData,id,response){

angular.forEach(originalData, function (item,key) {

if(item.id == id){

originalData[key] = response;

}

});

return originalData;

}

create one another folder “packages” and create file dirPagination.js(public/app/packages/dirPagination.js) and put code of following link:

dirPagination.js

Ok, at last you have create another one folder call “services” and create file myServices.js(public/app/services/myServices.js).

myServices.js

app.factory('dataFactory', function($http) {

var myService = {

httpRequest: function(url,method,params,dataPost,upload) {

var passParameters = {};

passParameters.url = url;

if (typeof method == 'undefined'){

passParameters.method = 'GET';

}else{

passParameters.method = method;

}

if (typeof params != 'undefined'){

passParameters.params = params;

}

if (typeof dataPost != 'undefined'){

passParameters.data = dataPost;

}

if (typeof upload != 'undefined'){

passParameters.upload = upload;

}

var promise = $http(passParameters).then(function (response) {

if(typeof response.data == 'string' && response.data != 1){

if(response.data.substr('loginMark')){

location.reload();

return;

}

$.gritter.add({

title: 'Application',

text: response.data

});

return false;

}

if(response.data.jsMessage){

$.gritter.add({

title: response.data.jsTitle,

text: response.data.jsMessage

});

}

return response.data;

},function(){

$.gritter.add({

title: 'Application',

text: 'An error occured while processing your request.'

});

});

return promise;

}

};

return myService;

});


Step 5: Create View

This is a last step and you have to create first app.blade.php file for theme setting, so let’s create app.blade.php(resources/views/app.blade.php) and put following code :

app.blade.php

<html lang="en">

<head>

<title>Laravel 5.2</title>

<!-- Fonts -->

<link href='//fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>

<!-- Angular JS -->

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-route.min.js"></script>

<!-- MY App -->

<script src="{{ asset('/app/packages/dirPagination.js') }}"></script>

<script src="{{ asset('/app/routes.js') }}"></script>

<script src="{{ asset('/app/services/myServices.js') }}"></script>

<script src="{{ asset('/app/helper/myHelper.js') }}"></script>

<!-- App Controller -->

<script src="{{ asset('/app/controllers/ItemController.js') }}"></script>

</head>

<body ng-app="main-App">

<nav >

<div >

<div >

<button type="button" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">

<span >Toggle Navigation</span>

<span ></span>

<span ></span>

<span ></span>

</button>

<a href="#">Laravel 5.2</a>

</div>

<div id="bs-example-navbar-collapse-1">

<ul >

<li><a href="#/">Home</a></li>

<li><a href="#/items">Item</a></li>

</ul>

</div>

</div>

</nav>

<div >

<ng-view></ng-view>

</div>

</body>

</html>

Ok, now we need to create templates folder in views folder and need to add three html file, i am going to create that so give name properly and add that.

1.resources/views/templates/home.html

<h2>Welcome to Dashboard</h2>

2.resources/views/templates/items.html

<div >

<div >

<div >

<h1>Item Management</h1>

</div>

<div style="padding-top:30px">

<div style="display:inline-table">

<div >

<input type="text" placeholder="Search" ng-change="searchDB()" ng-model="searchText" name="table_search" title="" tooltip="" data-original-title="Min character length is 3">

<span >Search</span>

</div>

</div>

<button data-toggle="modal" data-target="#create-user">Create New</button>

</div>

</div>

</div>

<table >

<thead>

<tr>

<th>No</th>

<th>Title</th>

<th>Description</th>

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

</tr>

</thead>

<tbody>

<tr dir-paginate="value in data | itemsPerPage:5" total-items="totalItems">

<td>{{ $index + 1 }}</td>

<td>{{ value.title }}</td>

<td>{{ value.description }}</td>

<td>

<button data-toggle="modal" ng-click="edit(value.id)" data-target="#edit-data" >Edit</button>

<button ng-click="remove(value,$index)" >Delete</button>

</td>

</tr>

</tbody>

</table>

<dir-pagination-controls on-page-change="pageChanged(newPageNumber)" template-url="templates/dirPagination.html" ></dir-pagination-controls>

<!-- Create Modal -->

<div id="create-user" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

<div role="document">

<div >

<form method="POST" name="addItem" role="form" ng-submit="saveAdd()">

<div >

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

<h4 id="myModalLabel">Create Item</h4>

</div>

<div >

<div >

<div >

<div >

<strong>Title : </strong>

<div >

<input ng-model="form.title" type="text" placeholder="Name" name="title" required />

</div>

</div>

<div >

<strong>Description : </strong>

<div >

<textarea ng-model="form.description" required>

</textarea>

</div>

</div>

</div>

<button type="button" data-dismiss="modal">Close</button>

<button type="submit" ng-disabled="addItem.$invalid" >Submit</button>

</div>

</div>

</form>

</div>

</div>

</div>

</div>

<!-- Edit Modal -->

<div id="edit-data" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

<div role="document">

<div >

<form method="POST" name="editItem" role="form" ng-submit="saveEdit()">

<input ng-model="form.id" type="hidden" placeholder="Name" name="name" />

<div >

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

<h4 id="myModalLabel">Edit Item</h4>

</div>

<div >

<div >

<div >

<div >

<div >

<input ng-model="form.title" type="text" placeholder="Name" name="title" required />

</div>

</div>

<div >

<div >

<textarea ng-model="form.description" required>

</textarea>

</div>

</div>

</div>

<button type="button" data-dismiss="modal">Close</button>

<button type="submit" ng-disabled="editItem.$invalid" >Submit</button>

</div>

</div>

</form>

</div>

</div>

</div>

</div>

3.resources/views/templates/dirPagination.html

Also see:Laravel 5 and Vue JS CRUD with Pagination example and demo from scratch

<ul ng-if="1 < pages.length">

<li ng-if="boundaryLinks" ng->

<a href="" ng-click="setCurrent(1)">«</a>

</li>

<li ng-if="directionLinks" ng->

<a href="" ng-click="setCurrent(pagination.current - 1)">‹</a>

</li>

<li ng-repeat="pageNumber in pages track by $index" ng->

<a href="" ng-click="setCurrent(pageNumber)">{{ pageNumber }}</a>

</li>

<li ng-if="directionLinks" ng->

<a href="" ng-click="setCurrent(pagination.current + 1)">›</a>

</li>

<li ng-if="boundaryLinks" ng->

<a href="" ng-click="setCurrent(pagination.last)">»</a>

</li>

</ul>

Ok, now we are ready to run our web application with crud, search and pagination, open your laravel application in browser and check pls,

IF you want to download this from git then you can download from here GitHub

Hope this code and post will helped you for implement Laravel 5.2 and AngularJS CRUD with Search and Pagination Example.. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

1  +  9  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US