Ananth Raj L
Ananth Raj L

Reputation: 11

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

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.

Upvotes: 1

Views: 5265

Answers (2)

Payam Yasaie
Payam Yasaie

Reputation: 71

You can just simply do the code below, when dependsOn is called, it will also call relatableTypes, so you will have it in the request.

The problem with session is, it will keep the value even if you are creating different resource.

BelongsTo::make('Make'),

BelongsTo::make('Type')->dependsOn('make', fn () => null),
public static function relatableTypes(Request $request, Builder $query): Builder
{
    // Just in case that request didn't include the input, 
    // like when it's called within `Vue` through `AssociatableController`
    $dependsOn = json_decode(base64_decode($request->string('dependsOn')));

    $makeId = $request->input('make') ?: $dependsOn->make

    return $query->where('make_id', $makeId);
}

Upvotes: 1

Helios Live
Helios Live

Reputation: 153

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);
    }
}

Upvotes: 4

Related Questions