简体   繁体   中英

Use one table for different resource in Laravel Nova

I'm trying to create something like a blogging system inside the Laravel Nova.

I have a table named articles as well as abstract model AbstractArctile .
I also have 3 categories:

  • News - App\Models\News\Article extending the App\Models\Abstract\AbstractArticle
  • Digests - App\Models\Digests\Article extending the App\Models\Abstract\AbstractArticle
  • Offtopic - App\Models\Offtopic\Article extending the App\Models\Abstract\AbstractArticle

The table articles has a field named category , and there are 3 types of categories: news, digests, offtopic .

Besides the extending the abstract model, each resource model also has one attribute defined, which is it's category in the following manner:

/**
 * To which category this article belongs to
 * @var array
 */
protected $attributes = [
    'category'  =>  'news'
];

I have no problem creating the articles under the specified categories in the Nova, however, instead of showing the articles from specified category, it displays articles from all categories on all resources.

Is there a way to display articles only from certain category on a given resource?

Summary

One abstract model -> 3 resources extending that model (with category attribute defined) -> how to display only items from that category inside the nova resource?

You can make use of Laravel eloquent query scope .

Add global scope like below to all 3 models ( App\Models\News\Article , App\Models\Digests\Article , App\Models\Offtopic\Article ), which is a easy way to make sure every query for a given model receives category constrains.

protected static function boot()
{
    parent::boot();

    static::addGlobalScope('category', function (Builder $builder) {
        $builder->where('category', 'news'); // Change the value depends on the model
    });
}

Hope this will help you.

In Nova, you can use indexQuery,detailQuery and editQuery as well and customize your resource results.

https://nova.laravel.com/docs/4.0/resources/authorization.html#index-filtering

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM