To integrate Yajra DataTables with Laravel 11's validation rules, you can follow these steps:
1. Modify the DataTable Class:
In your DataTable class (e.g., `UsersDataTable`), you can override the `query()` method to apply validation rules to the query:
php
public function query(User $model): QueryBuilder
{
$query = $model->newQuery();
return $this->applyScopes($query);
}
protected function applyScopes($query)
{
$request = request();
if ($request->has('name')) {
$query->where('name', 'like', "%{$request->get('name')}%");
}
if ($request->has('email')) {
$query->where('email', 'like', "%{$request->get('email')}%");
}
return $query;
}
In this example, we're applying validation rules to the query based on the `name` and `email` parameters in the request. You can add more validation rules as needed for your specific columns.
2. Update the View:
In your view, you can add the validation functionality to the DataTable:
html
<table class="table table-bordered data-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
<th>Updated At</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
@push('scripts')
<script>
$(function () {
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('users.index') }}",
data: function (d) {
d.name = $('input[name=name]').val();
d.email = $('input[name=email]').val();
}
},
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'created_at', name: 'created_at'},
{data: 'updated_at', name: 'updated_at'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$('input[name=name], input[name=email]').on('change', function() {
table.draw();
});
});
</script>
@endpush
In this example, we're adding input fields for the `name` and `email` columns. When the user types in the input fields, the DataTable will automatically apply the validation rules and filter the data based on the entered values.
By following these steps, you can integrate Yajra DataTables with Laravel 11's validation rules. The package provides a flexible API for applying validation rules to the DataTable queries and updating the table based on the validation results.
Citations:[1] https://www.elegantlaravel.com/article/yajra-datatables-integration-in-laravel-step-by-step-guide
[2] https://www.youtube.com/watch?v=fQDulbC3Smc
[3] https://itcodstuff.com/blog/laravel-yajra-datatables-tutorial/
[4] https://www.itsolutionstuff.com/post/how-to-use-yajra-datatables-in-laravel-6example.html
[5] https://yajrabox.com/docs/laravel-datatables/10.0/quick-starter