Laravel 12- Get Data Listing on Page

Laravel 12- Get Data Listing on Page

In this tutorial, we will walk through the steps to implement a fully functional user listing page using DataTables in Laravel 12. This feature will allow you to display a paginated, sortable, and searchable list of users. The user data will be fetched dynamically through an API route, and displayed using the powerful DataTables jQuery plugin for better UX and performance.

Step 1: Set Up the Route

In routes/web.php, define the routes for rendering the view and fetching the data:

use App\Http\Controllers\DataListingController; Route::controller(DataListingController::class)->group(function () { Route::middleware('auth')->group(function () { // Route to render the listing page Route::get('listing/page', 'index')->name('listing.page'); // Route to fetch data for the DataTable Route::get('get-data-user/listing', 'getData')->name('get-data-user.listing'); }); });

This ensures that only authenticated users can access the listing page and the DataTable data.

Step 2: Create the Controller

Create the controller to manage the data and view rendering.

Run the following Artisan command to create the controller:

php artisan make:controller DataListingController

Then, open app/Http/Controllers/DataListingController.php and add the following methods:

namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Carbon\Carbon; class DataListingController extends Controller { // Render the data listing view public function index() { return view('data-listing.index'); } // Fetch data for the DataTable public function getData(Request $request) { // DataTables parameters $draw = $request->get('draw'); $start = $request->get("start"); $rowPerPage = $request->get("length"); $order = $request->get('order'); $columns = $request->get('columns'); $search = $request->get('search'); // Column ordering $columnIndex = $order[0]['column']; $columnName = $columns[$columnIndex]['data']; $columnSortOrder = $order[0]['dir']; // asc or desc // Search term $searchValue = $search['value']; // Base query for users $users = DB::table('users'); // Count total records without filtering $totalRecords = $users->count(); // Define searchable columns $searchColumns = [ 'name', 'user_id', 'email', 'position', 'phone_number', 'join_date', 'role_name', 'status', 'department' ]; // Count total records with filtering $totalRecordsWithFilter = $users->where(function ($query) use ($searchValue, $searchColumns) { foreach ($searchColumns as $column) { $query->orWhere($column, 'like', "%{$searchValue}%"); } })->count(); // Fetch filtered records with sorting and pagination $records = $users->where(function ($query) use ($searchValue, $searchColumns) { foreach ($searchColumns as $column) { $query->orWhere($column, 'like', "%{$searchValue}%"); } }) ->orderBy($columnName, $columnSortOrder) ->skip($start) ->take($rowPerPage) ->get(); // Badge class mapping for status $badgeClasses = [ 'Inactive' => 'bg-danger-subtle text-danger', 'Pending' => 'bg-primary-subtle text-primary', 'Suspended' => 'bg-warning-subtle text-warning', 'Active' => 'bg-success-subtle text-success', ]; $data_arr = []; foreach ($records as $key => $record) { $last_login = Carbon::parse($record->last_login)->diffForHumans(); $action = ' <div class="d-flex gap-2"> <button class="btn btn-info btn-sm" data-bs-toggle="offcanvas" data-bs-target="#viewUser" aria-controls="viewUser"> <i class="bi bi-eye"></i> </button> <button class="btn btn-warning btn-sm" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight"> <i class="bi bi-pencil"></i> </button> <button class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#modalDeleteUser"> <i class="bi bi-trash"></i> </button> </div>'; $statusText = $record->status; $badgeClass = $badgeClasses[$statusText] ?? 'bg-secondary-subtle text-secondary'; $status = "<span class=\"badge {$badgeClass}\">{$statusText}</span>"; $data_arr[] = [ "action" => $action, "no" => '<span class="id" data-id="'.$record->id.'">'.($start + $key + 1).'</span>', "name" => $record->name, "user_id" => '<span class="user_id">'.$record->user_id.'</span>', "email" => '<span class="email">'.$record->email.'</span>', "position" => '<span class="position">'.$record->position.'</span>', "phone_number" => '<span class="phone_number">'.$record->phone_number.'</span>', "join_date" => $record->join_date, "last_login" => $last_login, "role_name" => $record->role_name, "department" => '<span class="department">'.$record->department.'</span>', "status" => $status, ]; } // Prepare response in DataTables format $response = [ "draw" => intval($draw), "iTotalRecords" => $totalRecords, "iTotalDisplayRecords" => $totalRecordsWithFilter, "aaData" => $data_arr ]; return response()->json($response); } }

This controller handles the fetching of data for the DataTable with necessary filtering, sorting, and pagination.

Step 3: Create the View (Frontend)

Create the view file resources/views/data-listing/index.blade.php to display the DataTable:

@extends('layouts.app') @section('content') <div class="container"> <h2>User Listing</h2> <div class="table-responsive"> <table id="userListing" class="table table-striped nowrap"> <thead> <tr> <th class="th-active-fixed">Actions</th> <th>No</th> <th>Name</th> <th>User ID</th> <th>Email</th> <th>Position</th> <th>Phone</th> <th>Join Date</th> <th>Last Login</th> <th>Role</th> <th>Department</th> <th>Status</th> </tr> </thead> <tbody></tbody> </table> </div> </div> @endsection @push('scripts') <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/buttons/2.2.0/js/dataTables.buttons.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> <script src="https://cdn.datatables.net/buttons/2.2.0/js/buttons.html5.min.js"></script> <script> $(document).ready(function() { const table = $('#userListing').DataTable({ lengthMenu: [ [10, 25, 50, 100, 150], [10, 25, 50, 100, 150] ], buttons: ['pageLength'], pageLength: 10, order: [[5, 'desc']], scrollX: true, processing: true, serverSide: true, ajax: { url: "{{ route('get-data-user.listing') }}", }, columns: [ { data: 'action', orderable: false, searchable: false }, { data: 'no' }, { data: 'name' }, { data: 'user_id' }, { data: 'email' }, { data: 'position' }, { data: 'phone_number' }, { data: 'join_date' }, { data: 'last_login' }, { data: 'role_name' }, { data: 'department' }, { data: 'status' }, ] }); }); </script> @endpush

Step 4: Add DataTables CSS and JS

Ensure you include the necessary DataTables CSS and JS files in the layout or the specific page:

<!-- Include DataTables CSS --> <link href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" rel="stylesheet"> <!-- Include DataTables Buttons CSS --> <link href="https://cdn.datatables.net/buttons/2.2.0/css/buttons.dataTables.min.css" rel="stylesheet">

Step 5: Test the Implementation

  • Navigate to listing/page to see the DataTable in action.

  • DataTables will automatically handle the AJAX call to fetch user data, and you'll be able to search, paginate, and sort the table.

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close