Search and Pagination with CRUD Example in Laravel PHP Framework and AngularJS
In my previous post, you learn how you can create a simple CRUD(Create Read Update Delete) application with Laravel 5.2 , i hope after following steps you will create your first admin panel.
Now I will tell you that how to create application with search , pagination and CRUD in Laravel 5.2 and AngularJS, kindly follow each step to create your first web application having modules with create, edit, delete, list, search and pagination functionality. Using AngularJS it is much more easier to work with events and workin with Laravel AngularJs then it make your application awesome. You must have knowledge about basic AngularJS before goint to create CRUD Application in Laravel AngularJS.
Step 1: Create Product Table and ModuleIn First step, create migration file for product table using Laravel 5 php artisan command.Run following command :
php artisan make:migration create_products_table
After this command, you will see a migration file in following path database/migrations and you have to simply put following code in migration file to create products table.
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Database\Migrations\Migration;
- class CreateProductsTable extends Migration
- {
- public function up()
- {
- Schema::create('products', function (Blueprint $table) {
- $table->increments('id');
- $table->string('name');
- $table->text('details');
- $table->timestamps();
- });
- }
- public function down()
- {
- Schema::drop("products");
- }
- }
Save this migration file and run following command
php artisan migrate
After create `products` table, yor should create model for product table.Create file in following path app/Product.php and put bellow couple of code in Product.php file:
app/Product.php
- namespace App;
- use Illuminate\Database\Eloquent\Model;
- class Product extends Model
- {
- public $fillable = ['name','details'];
- }
Now we will create ProductController.php
in following path app/Http/Controllers, all request(lists, create, edit, delete ,search and pagination) will manage by this ProductCRUDController.php
file.
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use App\Http\Requests;
- use App\Http\Controllers\Controller;
- use App\Product;
- class ProductController extends Controller
- {
- /**
- * Display a listing of the resource.
- *
- * @return Response
- */
- public function index(Request $request)
- {
- $input = $request->all();
- $products=Product::query();
- if($request->get('search')){
- $products = $products->where("name", "LIKE", "%{$request->get('search')}%");
- }
- $products = $products->paginate(5);
- return response($products);
- }
- /**
- * Store a newly created resource in storage.
- *
- * @return Response
- */
- public function store(Request $request)
- {
- $input = $request->all();
- $create = Product::create($input);
- return response($create);
- }
- /**
- * Show the form for editing the specified resource.
- *
- * @param int $id
- * @return Response
- */
- public function edit($id)
- {
- $product = Product::find($id);
- return response($product);
- }
- /**
- * Update the specified resource in storage.
- *
- * @param int $id
- * @return Response
- */
- public function update(Request $request,$id)
- {
- $input = $request->all();
- $product=Product::find($id);
- $product->update($input);
- $product=Product::find($id);
- return response($product);
- }
- /**
- * Remove the specified resource from storage.
- *
- * @param int $id
- * @return Response
- */
- public function destroy($id)
- {
- return Product::where('id',$id)->delete();
- }
- }
Now we will add some route in routes.php
. First add resource route for products module and another route for template route. using template route we will get html template for our app. So let's add below content in route file :
- <?php
- /*
- |--------------------------------------------------------------------------
- | Routes File
- |--------------------------------------------------------------------------
- |
- | Here is where you will register all of the routes in an application.
- | It's a breeze. Simply tell Laravel the URIs it should respond to
- | and give it the controller to call when that URI is requested.
- |
- */
- Route::get('/', function () {
- return view('app');
- });
- /*
- |--------------------------------------------------------------------------
- | Application Routes
- |--------------------------------------------------------------------------
- |
- | This route group applies the "web" middleware group to every route
- | it contains. The "web" middleware group is defined in your HTTP
- | kernel and includes session state, CSRF protection, and more.
- |
- */
- Route::group(['middleware' => ['web']], function () {
- Route::resource('products', 'ProductController');
- });
- // Angular HTML Templates
- Route::group(array('prefix'=>'/htmltemplates/'),function(){
- Route::get('{htmltemplates}', array( function($htmltemplates)
- {
- $htmltemplates = str_replace(".html","",$htmltemplates);
- View::addExtension('html','php');
- return View::make('htmltemplates.'.$htmltemplates);
- }));
- });
First we will create a separate directory with name `app` in public directory public/app where we will put all angularjs files so that it will be easier to manage files
Create route.js
file in following path public/app/route.js
- var app = angular.module('main-App',['ngRoute','angularUtils.directives.dirPagination']);
- app.config(['$routeProvider',
- function($routeProvider) {
- $routeProvider.
- when('/', {
- templateUrl: 'htmltemplates/home.html',
- controller: 'AdminController'
- }).
- when('/products', {
- templateUrl: 'htmltemplates/products.html',
- controller: 'ProductController'
- });
- }]);
- app.value('apiUrl', 'public path url');
app.value
define global variable which will be injected in controller where we use this variable
Now we will create a controller directory in app directory with name `controllers` and create ProductController.js
file in following path public/app/controllers/ProductController.js
- app.controller('AdminController', function($scope,$http){
- $scope.pools = [];
- });
- app.controller('ProductController', function(dataFactory,$scope,$http,apiUrl){
- $scope.data = [];
- $scope.libraryTemp = {};
- $scope.totalProductsTemp = {};
- $scope.totalProducts = 0;
- $scope.pageChanged = function(newPage) {
- getResultsPage(newPage);
- };
- getResultsPage(1);
- function getResultsPage(pageNumber) {
- if(! $.isEmptyObject($scope.libraryTemp)){
- dataFactory.httpRequest(apiUrl+'/products?search='+$scope.searchInputText+'&page='+pageNumber).then(function(data) {
- $scope.data = data.data;
- $scope.totalProducts = data.total;
- });
- }else{
- dataFactory.httpRequest(apiUrl+'/products?page='+pageNumber).then(function(data) {
- console.log(data);
- $scope.data = data.data;
- $scope.totalProducts = data.total;
- });
- }
- }
- $scope.dbSearch = function(){
- if($scope.searchInputText.length >= 3){
- if($.isEmptyObject($scope.libraryTemp)){
- $scope.libraryTemp = $scope.data;
- $scope.totalProductsTemp = $scope.totalProducts;
- $scope.data = {};
- }
- getResultsPage(1);
- }else{
- if(! $.isEmptyObject($scope.libraryTemp)){
- $scope.data = $scope.libraryTemp ;
- $scope.totalProducts = $scope.totalProductsTemp;
- $scope.libraryTemp = {};
- }
- }
- }
- $scope.saveAdd = function(){
- dataFactory.httpRequest('products','POST',{},$scope.form).then(function(data) {
- $scope.data.push(data);
- $(".modal").modal("hide");
- });
- }
- $scope.edit = function(id){
- dataFactory.httpRequest(apiUrl+'/products/'+id+'/edit').then(function(data) {
- console.log(data);
- $scope.form = data;
- });
- }
- $scope.updateProduct = function(){
- dataFactory.httpRequest(apiUrl+'/products/'+$scope.form.id,'PUT',{},$scope.form).then(function(data) {
- $(".modal").modal("hide");
- $scope.data = apiModifyTable($scope.data,data.id,data);
- });
- }
- $scope.remove = function(product,index){
- var result = confirm("Are you sure delete this product?");
- if (result) {
- dataFactory.httpRequest(apiUrl+'/products/'+product.id,'DELETE').then(function(data) {
- $scope.data.splice(index,1);
- });
- }
- }
- });
Now we will create a folder with name `myhelper` in app directory for helper.js
file, which will help to define helper functions.
- function apiModifyTable(mainData,id,response){
- angular.forEach(mainData, function (product,key) {
- if(product.id == id){
- mainData[key] = response;
- }
- });
- return mainData;
- }
Now we will create another directory `packages` and create dirPagination.js
file in following path public/app/packages/dirPagination.jsand put code of following link :
Now We will create another directory `services` and create services.js
file in following path public/app/myservices/services.js and put code of following link :
Step5: Create View
This is final step, where you have to create view files. So first start to create angularapp.blade.php
in following path resources/views/angularapp.blade.php and put following code :
- <!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">
- <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="http://www.expertphp.in/css/bootstrap.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/myservices/services.js') }}"></script>
- <script src="{{ asset('app/myhelper/helper.js') }}"></script>
- <!-- App Controller -->
- <script src="{{ asset('/app/controllers/ProductController.js') }}"></script>
- </head>
- <body ng-app="main-App">
- <nav class="navbar navbar-default">
- <div class="container-fluid">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapse-1-example">
- <span class="sr-only">Toggle Navigation</span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- <a class="navbar-brand" href="#">Laravel 5.2</a>
- </div>
- <div class="collapse navbar-collapse" id="collapse-1-example">
- <ul class="nav navbar-nav">
- <li><a href="#/">Home</a></li>
- <li><a href="#/products">Product</a></li>
- </ul>
- </div>
- </div>
- </nav>
- <div id="container_area" class="container">
- <ng-view></ng-view>
- </div>
- <!-- Scripts -->
- </body>
- </html>
Now we will create htmltemplates folder in following path resources/views/ and then create home.html
file in htmltemplates folder.
- <h2>Welcome to Landing Page</h2>
resources/views/htmltemplates/products.html
- <div class="row">
- <div class="col-lg-12 margin-tb">
- <div class="pull-left">
- <h1>Product Management</h1>
- </div>
- <div class="pull-right" style="padding-top:30px">
- <div class="box-tools" style="display:inline-table">
- <div class="input-group">
- <input type="text" class="form-control input-sm ng-valid ng-dirty" placeholder="Search" ng-change="dbSearch()" ng-model="searchInputText" name="table_search" title="" tooltip="" data-original-title="Minimum length of character is 3">
- <span class="input-group-addon">Search</span>
- </div>
- </div>
- <button class="btn btn-success" data-toggle="modal" data-target="#add-new-product">Create New Product</button>
- </div>
- </div>
- </div>
- <table class="table table-bordered pagin-table">
- <thead>
- <tr>
- <th>No</th>
- <th>Name</th>
- <th>Details</th>
- <th width="220px">Action</th>
- </tr>
- </thead>
- <tbody>
- <tr dir-paginate="value in data | productsPerPage:5" total-products="totalProducts">
- <td>{{ $index + 1 }}</td>
- <td>{{ value.name }}</td>
- <td>{{ value.details }}</td>
- <td>
- <button data-toggle="modal" ng-click="edit(value.id)" data-target="#edit-data" class="btn btn-primary">Edit</button>
- <button ng-click="remove(value,$index)" class="btn btn-danger">Delete</button>
- </td>
- </tr>
- </tbody>
- </table>
- <dir-pagination-controls class="pull-right" on-page-change="pageChanged(newPageNumber)" template-url="htmltemplates/dirPagination.html" ></dir-pagination-controls>
- <!-- Create Modal -->
- <div class="modal" id="add-new-product" tabindex="-1" role="dialog" aria-labelledby="myModalForLabel">
- <div class="modal-dialog" role="document">
- <div class="modal-content">
- <form method="POST" name="addProduct" role="form" ng-submit="saveAdd()">
- <input type="hidden" name="_token" value="{!! csrf_token() !!}">
- <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="myModalForLabel">Create Product</h4>
- </div>
- <div class="modal-body">
- <div class="row">
- <div class="col-xs-12 col-sm-12 col-md-12">
- <strong>Name : </strong>
- <div class="form-group">
- <input ng-model="form.name" type="text" placeholder="Product Name" name="name" class="form-control" required />
- </div>
- </div>
- <div class="col-xs-12 col-sm-12 col-md-12">
- <strong>Details : </strong>
- <div class="form-group" >
- <textarea ng-model="form.details" class="form-control" required>
- </textarea>
- </div>
- </div>
- </div>
- <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
- <button type="submit" ng-disabled="addProduct.$invalid" class="btn btn-primary">Submit</button>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- <!-- Edit Modal -->
- <div class="modal fade" id="edit-data" tabindex="-1" role="dialog" aria-labelledby="myModalForLabel">
- <div class="modal-dialog" role="document">
- <div class="modal-content">
- <form method="POST" name="editProduct" role="form" ng-submit="updateProduct()">
- <input ng-model="form.id" type="hidden" placeholder="Name" name="name" class="form-control" />
- <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="myModalForLabel">Edit Product</h4>
- </div>
- <div id="modal_body_container" class="modal-body">
- <div class="row">
- <div class="col-xs-12 col-sm-12 col-md-12">
- <div class="form-group">
- <input ng-model="form.name" type="text" placeholder="Name" name="name" class="form-control" required />
- </div>
- </div>
- <div class="col-xs-12 col-sm-12 col-md-12">
- <div class="form-group">
- <textarea ng-model="form.details" class="form-control" required>
- </textarea>
- </div>
- </div>
- </div>
- <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
- <button type="submit" ng-disabled="editProduct.$invalid" class="btn btn-primary create-crud">Submit</button>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
resources/views/htmltemplates/dirPagination.html
- <ul class="pagination pull-right" ng-if="1 < pages.length">
- <li ng-if="boundaryLinks" ng-class="{ disabled : pagination.current == 1 }">
- <a href="" ng-click="setCurrent(1)">«</a>
- </li>
- <li ng-if="directionLinks" ng-class="{ disabled : pagination.current == 1 }">
- <a href="" ng-click="setCurrent(pagination.current - 1)">‹</a>
- </li>
- <li ng-repeat="pageNumber in pages track by $index" ng-class="{ active : pagination.current == pageNumber, disabled : pageNumber == '...' }">
- <a href="" ng-click="setCurrent(pageNumber)">{{ pageNumber }}</a>
- </li>
- <li ng-if="directionLinks" ng-class="{ disabled : pagination.current == pagination.last }">
- <a href="" ng-click="setCurrent(pagination.current + 1)">›</a>
- </li>
- <li ng-if="boundaryLinks" ng-class="{ disabled : pagination.current == pagination.last }">
- <a href="" ng-click="setCurrent(pagination.last)">»</a>
- </li>
- </ul>