Laravel8 attribute or appends in query where
I want to reach the record
if in model User
class User extends Model {
protected $fillable = ['last_name','first_name'];
protected $appends = [
'full_name',
];
public function getFullNameAttribute(): string
{
return $this->first_name . ' ' . $this->last_name;
}
}
in request
full_name = 'John Johans';
How to get database record if
User::query()->where('full_name',$request->full_name)
If I use this record the answer will be an error that full_name does not exist in the database
I would like to use "where" for "appends"
User::query()->where(**MY ATTRIBUTE**,$request)->first()
it is possible ?
2 Options:
- Use
CONCAT
in yourWHERE
clause
User::query()
->whereRaw('CONCAT(first_name, " ", last_name) = "?"', [$request->full_name])
->get();
- Get all the users and then filter in the resulting
Collection
.
User::cursor()
->filter(function ($user) use ($request) {
return $user->full_name == $request->full_name;
})
->collect();
User::cursor()
->filter(fn($user) => $user->full_name == $request->full_name)
->collect();
Letting SQL do the filtering (Option 1) is probably the better choice.