Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nova Filters - filter a resource with a belongsTo relationship?

How can i create a Nova filter that will allow me to filter my Question resource by another resource called Module?

The question belongsTo to the module (module_id is FK on Questions).

So for the apply method i have:

public function apply(Request $request, $query, $value)
{
    return $query->where('module_id', $value);
}

I'm struggling with the options method. I would like to have the module->name as the key and the module->id as the value but would like to display all modules.

like image 461
Adnan Avatar asked Oct 03 '18 12:10

Adnan


People also ask

How do I use relationship fields in Nova?

Once you add relationship fields to your Nova resources, you'll start to experience the full power of the Nova dashboard, as the resource detail screen will allow you to quickly view and search a resource's related models: The HasOne field corresponds to a hasOne Eloquent relationship.

What is the filter component in Nova?

This component contains the template and logic for your filter when it is displayed in the filter dropdown menu. By default, the component displays a simple select filter component, along with the needed code for updating the filter's state. Custom Nova filters use Vuex to manage their state.

How do I create a custom-filter using Nova?

When generating a filter using the nova:custom-filter command, the filter name you pass to the command should follow the Composer vendor/package format. So, if we were building an age-range filter, we might run the following command:

How do I make a belongsto relationship nullable?

If you would like your BelongsTo relationship to be nullable, chain the nullable method onto the field's definition: When a BelongsTo field is shown on a resource creation / update screen, a drop-down selection menu or search menu will display the "title" of the resource.


1 Answers

Use Module model to retrieve all & use collection method pluck to get name => id as key value pair.

public function options(Request $request)
{
    $models = \App\Module::all();
    return $models->pluck('id', 'name')->all();
}
like image 62
Saumini Navaratnam Avatar answered Oct 28 '22 04:10

Saumini Navaratnam