I think I solved it using
public function scopeFindName($query, $string) {
return $query->where('name', $string)->first();
}
inside my model. Is it okay to do it like this?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
So I have 3 tables to define a many to many relationship:
preferences with fields id and name -> name field is unique
users - the default laravel users table
preference_user -> pivot table with fields user_id, preference_id, value
Right now, if I want to attach a preference to a user, I need to do it like this:
Case: I catch a request inside the controller that contains the name of the preference
$user = Auth::user();
$preference = Preference::where('name', $request->preference)->first();
$user->preferences()->attach($preference);
Is there any way I can do this easier?
Like
Preference::find('namehere');
Please or to participate in this conversation.