Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sergiuwd's avatar

Use name to find value in table

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');
0 likes
4 replies
sergiuwd's avatar

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?

cviv's avatar

this one, but needs more refinement..

Preference::whereName($request->preference)->get();
cviv's avatar

@sergiuwd did you try the output of your code? I would do it this way

public function scopeFindName($query, $string) {
     return $query->where('name', $string);
}

then

Preference::findName($string)->first();
sergiuwd's avatar

@cviv the name is unique, that's why I choose to call first() inside the custom method

Please or to participate in this conversation.