Introduction
Laravel Volt is a lightweight, reactive frontend framework that integrates seamlessly with Laravel. It enables developers to build dynamic, interactive user interfaces using Blade-like syntax without relying on heavy JavaScript frameworks. In this guide, we’ll walk through building a fully featured DataTable in one Volt file. This DataTable includes advanced functionalities like pagination, per-page selection, filtering, searching, and CRUD actions (edit, delete, and show).
This article is optimized for SEO with focused keywords such as “Laravel Volt,” “DataTable,” “pagination,” “filters,” “CRUD actions,” and “Laravel developer guide.” Whether you are a seasoned Laravel developer or just getting started, this guide will help you implement a robust and responsive DataTable for your application.
Prerequisites
Before getting started, ensure that you have the following:
- A Laravel project set up (Laravel 8 or above recommended).
- Laravel Volt installed. You can install it via Composer:
composer require laravel/volt
A database table (e.g., a users
table) with columns such as id
, name
, email
, and role
.
Building the DataTable with Laravel Volt
In this example, we are creating a single Volt file that handles everything. The file will include:
- Pagination: Dynamically load a set number of records.
- Per-Page Selection: Allow users to choose how many records to display.
- Filters: Filter data based on specific criteria (e.g., user roles).
- Search: Provide keyword search functionality across key columns.
- CRUD Actions: Add Edit, Delete, and Show buttons to manage records.
Step-by-Step Implementation
Save the following code as resources/views/datatable.volt.php
:
@php
use App\Models\User;
// Initialize variables for search, sorting, and filtering
$search = $search ?? '';
$sortField = $sortField ?? 'id';
$sortDirection = $sortDirection ?? 'asc';
$perPage = $perPage ?? 10;
$filterRole = $filterRole ?? '';
// Build query based on input parameters
$query = User::query();
if ($search) {
$query->where('name', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%");
}
if ($filterRole) {
$query->where('role', $filterRole);
}
$users = $query->orderBy($sortField, $sortDirection)
->paginate($perPage);
@endphp
<div class="container mx-auto p-4">
<!-- Search and Filters Section -->
<div class="flex flex-col md:flex-row md:justify-between items-center mb-4 space-y-2 md:space-y-0">
<input wire:model="search" type="text" placeholder="Search by name or email..." class="border rounded px-2 py-1 w-full md:w-1/3">
<select wire:model="filterRole" class="border rounded px-2 py-1 w-full md:w-1/5">
<option value="">All Roles</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
<select wire:model="perPage" class="border rounded px-2 py-1 w-full md:w-1/5">
<option value="5">5 per page</option>
<option value="10">10 per page</option>
<option value="20">20 per page</option>
</select>
</div>
<!-- DataTable Section -->
<div class="overflow-x-auto">
<table class="w-full border-collapse border">
<thead>
<tr class="bg-gray-200">
<th class="border px-2 py-1 cursor-pointer" wire:click="$set('sortField', 'id')">ID</th>
<th class="border px-2 py-1 cursor-pointer" wire:click="$set('sortField', 'name')">Name</th>
<th class="border px-2 py-1 cursor-pointer" wire:click="$set('sortField', 'email')">Email</th>
<th class="border px-2 py-1">Role</th>
<th class="border px-2 py-1">Actions</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td class="border px-2 py-1">{{ $user->id }}</td>
<td class="border px-2 py-1">{{ $user->name }}</td>
<td class="border px-2 py-1">{{ $user->email }}</td>
<td class="border px-2 py-1">{{ $user->role }}</td>
<td class="border px-2 py-1 flex space-x-2">
<!-- Show Button -->
<a href="{{ route('users.show', $user->id) }}" class="bg-blue-500 text-white px-2 py-1 rounded">Show</a>
<!-- Edit Button -->
<a href="{{ route('users.edit', $user->id) }}" class="bg-green-500 text-white px-2 py-1 rounded">Edit</a>
<!-- Delete Button -->
<button wire:click="deleteUser({{ $user->id }})" class="bg-red-500 text-white px-2 py-1 rounded">Delete</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<!-- Pagination Links -->
<div class="mt-4">
{{ $users->links() }}
</div>
</div>
@volt
/**
* Delete a user by ID.
*
* @param int $userId
*/
function deleteUser($userId) {
// Find the user and delete from the database
User::findOrFail($userId)->delete();
// Optionally, you can add a success message or reload logic here.
}
@endvolt
Code Explanation
1. Variables & Query Building
- Search, Sorting, and Filtering:
The code initializes variables like$search
,$sortField
,$sortDirection
,$perPage
, and$filterRole
. These variables allow users to dynamically filter and sort the table data. - Query Customization:
Depending on the input, the query is built using Eloquent methods to filter based on user name, email, or role. It also handles sorting and pagination.
2. Interactive UI Elements
- Search Input & Dropdowns:
The search box lets users filter results by keywords. Two dropdown menus allow users to select a specific role and determine how many records to display per page. - Table Headers:
Clickable headers let users change the sort field (e.g., sorting byid
,name
, oremail
).
3. DataTable with CRUD Actions
- CRUD Actions Column:
Each row includes three buttons:- Show: Redirects to the detailed view of the user.
- Edit: Redirects to the edit form.
- Delete: Calls a Volt function to delete the user record.
- Laravel Routes:
Make sure that yourweb.php
file defines the routesusers.show
andusers.edit
for the Show and Edit actions respectively:
Route::get('/users/{user}', [UserController::class, 'show'])->name('users.show');
Route::get('/users/{user}/edit', [UserController::class, 'edit'])->name('users.edit');
4. Volt Functionality
- Inline Volt Function (@volt Block):
The Volt functiondeleteUser
is defined to handle the deletion of a user. This keeps your code concise and within a single file, enhancing developer productivity.
Developer-Friendly Features
- Single File Setup:
Developers can quickly integrate and modify the DataTable without navigating multiple files. - Clean Code Example:
Well-commented code makes it easier to understand the logic behind search, filtering, and CRUD actions. - Interactive Elements:
The inclusion of interactive features such as sorting and dynamic pagination improves user experience.