Yes, it is possible to link to a filtered Laravel Nova resource. One way to achieve this is by passing the filter parameters as query string parameters in the URL. Here's an example of how to do this:
- In your
Genresresource, define an inline action that redirects to theBooksresource with the corresponding genre filter applied. Here's an example:
public function actions(Request $request)
{
return [
(new Action('relatedBooks'))
->onlyOnTableRow()
->canSee(function ($request) {
return true; // Add your authorization logic here
}),
];
}
public function relatedBooks(Request $request, $resource)
{
$genreId = $resource->id;
$filter = base64_encode(json_encode([
[
'class' => GenreFilter::class,
'value' => $genreId,
],
]));
return Action::redirect('/nova/resources/books?filters=' . $filter);
}
- In the
Booksresource, define a filter that filters the books by genre. Here's an example:
class GenreFilter extends Filter
{
public function apply(Request $request, $query, $value)
{
return $query->where('genre_id', $value);
}
public function options(Request $request)
{
return Genre::pluck('name', 'id')->toArray();
}
}
-
When the user clicks on the "Related Books" inline action in the
Genresresource, they will be redirected to theBooksresource with the corresponding genre filter applied. The filter parameters will be passed as a base64-encoded JSON string in thefiltersquery string parameter. -
In the
Booksresource, you can decode the filter parameters and apply them to the query builder. Here's an example:
public static function indexQuery(NovaRequest $request, $query)
{
if ($request->filters) {
$filters = json_decode(base64_decode($request->filters), true);
foreach ($filters as $filter) {
$query = app($filter['class'])->apply($request, $query, $filter['value']);
}
}
return $query;
}
This code decodes the filters query string parameter, applies each filter to the query builder, and returns the modified query builder.