7

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?

Ya Basha
  • 1,902
  • 6
  • 30
  • 54
  • Did you try to create a [lense](https://nova.laravel.com/docs/1.0/lenses/defining-lenses.html) to customize the underlying eloquent query? – Sven Dec 23 '18 at 04:46
  • no, but i'll consider that, thanx for the hint ;) – Ya Basha Dec 23 '18 at 07:21

2 Answers2

16

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);
}
Saumini Navaratnam
  • 8,439
  • 3
  • 42
  • 70
4

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()).

Sven
  • 1,450
  • 3
  • 33
  • 58