Chey Luna
Chey Luna

Reputation: 70

How to do a multiple select with raw query using Eloquent in Laravel 5.1

I made a query which gets all the column data of a table and an additional custom column aliased as 'distance'. Right now the query looks like this:

$restaurants = DB::table(DB::raw('restaurants'))
    ->select(
        'restaurants.id',
        'restaurants.name',
        'restaurants.about',
        'restaurants.contact_details',
        'restaurants.address',
        'restaurants.city',
        'restaurants.lat',
        'restaurants.long',
        'restaurants.cuisines',
        DB::raw(*some computation here* . " as distance")
    )
    ->get();

Basically, my query should look like this in SQL:

SELECT *, *some computation here* as distance FROM restaurants

Is there a way to simplify this using Eloquent? Right now I need to manually specify all the columns just so I could add the DB::raw select statement.

Upvotes: 3

Views: 11637

Answers (1)

Roj Vroemen
Roj Vroemen

Reputation: 1892

This should work:

$restaurants = DB::table('restaurants')
    ->select(
        'restaurants.*',
        DB::raw(*some computation here* . " as distance")
    )
    ->get();

Upvotes: 8

Related Questions