Laravel attribute casting

4190 views laravel

Here all values of metakey and metavalue are string type.hence price 200 and 100 both are string too. I want to filter users within minimum and maximum price.But i am struggling to do so because 200 and 100 both are string.




UserMeta table

id | user_id | metaKey | metavalue

  1 | 1        | city     | kolkata

  2 |2         |city      | london

  3 |8         |city      |london

  4 |1         |price     |200

   5|8         |price     |100

what I tried:

return User::whereHas('UserMeta', function ($query) use ($value) {
    $query->where('meta_key', 'price')
          ->where('meta_value','< =', intval($value));

answered question

what is the output of what you tried?

with intval($value) gives no results. with where('meta_value','< =', $value) gives wrong results. like when i try to filter with 2001 it works fine. but not working when i try to filter with 1999

1 Answer


Try this method otherwise You need to cast attributes in Eloquent by adding a protected $casts array to your model.

return User::whereHas('UserMeta', function ($query) use ($value) {
$query->where('meta_key', 'price')
      ->where('meta_value','< =', (int)$value);

posted this

Have an answer?


Please login first before posting an answer.