To display a user list in Laravel using the Yajra DataTables package, you can follow these steps:
- Install the Yajra DataTables package: Run the following command to install the Yajra DataTables package:
composer require yajra/laravel-datatables-oracle:^9.0
- Add the Yajra DataTables service provider: Open the
config/app.phpfile and add the following line to theprovidersarray:
Yajra\DataTables\DataTablesServiceProvider::class,
- Publish the Yajra DataTables configuration file: Run the following command to publish the Yajra DataTables configuration file:
php artisan vendor:publish --tag=config
This will create a datatables.php file in the config directory.
- Create a route to fetch the users data: In your
routes/web.phpfile, create a route to fetch the users data using the Yajra DataTables package:
Route::get('users', 'UserController@index')->name('users.index');
- Create a controller: Create a
UserControllercontroller by running the following command:
php artisan make:controller UserController
- Define the index method: In the
UserControllercontroller, define theindexmethod to fetch the users data and return it as a JSON response:
use App\User;
use DataTables;
public function index()
{
$users = User::select(['id', 'name', 'email']);
return DataTables::of($users)->make(true);
}
This method selects only the id, name, and email fields from the users table and passes them to the DataTables::of() method to create a DataTable instance.
- Create a view: Create a
users.blade.phpview file in theresources/viewsdirectory and add the following code:
@extends('layouts.app')
@section('content')
<table id="users-table" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
</table>
@endsection
@push('scripts')
<script>
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route("users.index") }}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
]
});
});
</script>
@endpush
This view extends the layouts.app layout and defines a table with an ID of users-table. It also includes a JavaScript block to initialize the DataTable instance using the server-side processing mode and the route to fetch the users data.
- Create a route to display the view: In your
routes/web.phpfile, create a route to display theusers.blade.phpview:
Route::get('/', function () {
return view('users');
});
- Include the DataTables assets: In your
layouts/app.blade.phpfile, include the DataTables CSS and JavaScript assets:
<!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css">
</head>
<body>
<div
.
No comments:
Post a Comment