Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display specific eloquent query in nova resource index view

I want to display the following eloquent in index view for nova resource

Post::where('frontpage', true)->get()

And perform Post model CRUD operations, How can I do that?

like image 602
Ya Basha Avatar asked Dec 22 '18 19:12

Ya Basha


Video Answer


2 Answers

You can simply override indexQuery of your Nova resource, Reference

/**
 * Build an "index" query for the given resource.
 *
 * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
 * @param  \Illuminate\Database\Eloquent\Builder  $query
 * @return \Illuminate\Database\Eloquent\Builder
 */
public static function indexQuery(NovaRequest $request, $query)
{
    return $query->where('frontpage', true);
}
like image 83
Saumini Navaratnam Avatar answered Oct 10 '22 13:10

Saumini Navaratnam


Nova utilizes the concept of lenses to do this.

Create a new lens from the command line:

php artisan nova:lens IsFrontpage

Modify the query() method in app/Nova/Lenses/IsFrontpage.php:

public static function query(LensRequest $request, $query)
{
    return $request->withOrdering($request->withFilters(
        $query->where('frontpage', '=', true)
    ));
}

Attach the lens to a resource:

public function lenses(Request $request)
{
    return [
        new IsFrontpage()
    ];
}

Access the lens in the Nova admin panel: /nova/resources/posts/lens/is-frontpage

Take a closer look at the Nova documentation to also customize the URL slug (see uriKey()) and the columns (see fields()).

like image 31
Sven Avatar answered Oct 10 '22 14:10

Sven