dependent field in laravel nova 4, dependsOn() method,

Viewed 319

Hi Im using laravel nova 4 and im not able to find any code for dependsOn() method for a dependent field. I have 2 models (1.type and 2. make) type belongs to make. in my resource, field function, i have codes like below BelongsTo::make('Make'), BelongsTo::make('Type'),

I want the type dropdown to be dependent on the make selected. Type has make_id as foreign key.

is there any method i can achieve this.

Thanks for the help in advance.

1 Answers

You need both dependent fields and relatable filtering. But technically since type already belongs to make you don't actually need to add the Make field.

https://nova.laravel.com/docs/4.0/resources/fields.html#dependent-fields https://nova.laravel.com/docs/4.0/resources/authorization.html#relatable-filtering

use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\FormData;
use Laravel\Nova\Http\Requests\NovaRequest;

BelongsTo::make('Make'),

BelongsTo::make('Type')
    ->dependsOn('make', function (BelongsTo $field, NovaRequest $request, FormData $formData) {
        session()->put('make_filter', $formData->make);
    }),

public static function relatableTypes(Request $request, $query)
{
    if($make = session()->get('make_filter')) {
        return $query->where('make_id', $make);
    }
}
Related