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

andyandy's avatar

Help me rewrite Eloquent (Query builder)

I have working script. With table:

RECORDS: id|name|text|latitude|longitude

return $builder->whereRaw('ST_Distance(point(latitude, longitude), point('.request('latitude').','.request('longitude').')) < '.$distance);

But I moved latitude/longitude into separate table, so I have:

RECORDS: id|name|text|city_id

CITIES: id|latitude|longitude

How do I rewrite the query builder?

0 likes
7 replies
Snapey's avatar

run it against the cities table and not the records table

Where you select the table is not shown here

andyandy's avatar

In Controller I call:

$records = Record::filteredRecords();
return view('searchResults', compact('records'));

Which refers to function in Model:

public static function filteredRecords()
    {
        return $records = app(Pipeline::class)
            ->send(Record::query())
            ->through([
                \App\Filters\Distance::class,
                ...
                ...
                ...
                ...
                ...
                ...
                \App\Filters\Text::class,
            ])->thenReturn()->paginate(10, ['*'], 'page');
    }

And I want to change only "\App\Filters\Distance::class," which is mentioned in my first post. And my question is about changing that Distance class alone.

Snapey's avatar
Snapey
Best Answer
Level 122

you will then have to add a join to the cities table

andyandy's avatar

This seems to work.

return $builder->leftjoin('cities', 'records.city_id', '=', 'cities.id')->whereRaw('ST_Distance(point(cities.latitude, cities.longitude), point(' . request('latitude') . ',' . request('longitude') . ')) < ' . $distance);

BUT in returned results, second table overwrites columns of first table. Eg. returned ID is not ID of Records (first table) but ID of Cities (second table).

andyandy's avatar

And overwriting problem seems to be solved by select('records.*')

return $builder->select('records.*')->leftjoin('cities', 'records.city_id', '=', 'cities.id')->whereRaw('ST_Distance(point(cities.latitude, cities.longitude), point(' . request('latitude') . ',' . request('longitude') . ')) < ' . $distance);

I'm marking it solved, although I don't understand this overwriting issue and don't have 100% confidence in this solution.

Please or to participate in this conversation.