Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Nova - Only load relationship with certain property in form dropdown

I have added a BelongsTo relationship field(relationship name: user) in my Nova app in resource named "Partner". So in the "create partner" form now I have a select element to choose a specific user.

The relationship I have written includes a condition:

$this->belongsTo('App\User')->where('role', 'partner');

In the select dropdown, instead of only showing users with role "partner", all users of the app are listing. How can I fix this issue?

User table : id, name, role
Partner table : id, user_id, name

Partner Model:

class Partner extends Model
{

  protected $fillable = [
    'name', 'email', 'user_id'
  ];

  public function User()
  {
      return $this->belongsTo('App\User')->where('role', 'partner');
  }

}

Nova Resource fields method for Partner:

public function fields(Request $request)
{
    return [
        Text::make('Name')->sortable(),
        ID::make()->sortable(),
        BelongsTo::make('User', 'user', 'App\Nova\User')->rules('required'),
        HasMany::make('Clients'),
    ];
}
like image 735
Vineeth Vijayan Avatar asked Nov 16 '18 04:11

Vineeth Vijayan


1 Answers

You need to add the relatableQuery for User under Partner Nova resource. No need the where condition in Partner model.

use Laravel\Nova\Http\Requests\NovaRequest;
...

public static function relatableUsers(NovaRequest $request, $query)
{
    return $query->where('role', 'partner');
}
like image 134
Saumini Navaratnam Avatar answered Jan 01 '23 07:01

Saumini Navaratnam