I'm trying to use raw select with Laravel Eloquent. But unfortunately I cannot use WHERE condition for aliased "SELECT AS" field (distance).
I get "Column not found: 1054 Unknown column 'distance' in 'where clause'" error.
How can I use "distance" as a condition with Eloquent?
Here is my code
$firebaseUsers = FirebaseUser::when( (!empty($distance)) , function ($query) use ($distance, $user) {
return $query->select('firebase_users.*', DB::raw("ST_Distance_Sphere( POINT(".$user->latitude.", ".$user->longitude."), POINT(latitude, longitude) ) as distance") )
->whereNotNull('latitude')
->whereNotNull('longitude')
->whereRaw('distance <= ?', [$distance * 1000]);
})
->where('firebase_id', '!=', $user->firebase_id)
->orderByRaw( "FIELD(paid_status, 'yes', 'no')" )
->orderBy('last_online', 'DESC')
->paginate(30);
->havingRaw('distance <= ?', [$distance * 1000]);
instead ofwhereRaw
. Personally, I'd create a view and then have Eloquent model deal with the view instead of this cabbage.. - N.B."Didn't work"
- absolutely does not help. HOW did it not work? IfhavingRaw
doesn't exist, tryhaving
. For derived columns, you can't usewhere
, you need to usehaving
. - N.B.