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'),
];
}
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With