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

moemenh_'s avatar

Laravel get model relations with select raw query

So I have copied a function from the internet to get all companies in your area. Now the function gets all the columns in the table that I need, but my table has relations with other tables and I want it to get the data of the other tables instead of only the id's.

This is the code to get all the companies in your area:

$companies = DB::table('companies')
    ->selectRaw(
        "id, owner, company_info, address, latitude, longitude,
        (6371 * acos( cos( radians(?))
        * cos( radians(latitude) )
        * cos( radians( longitude ) - radians(?))
        + sin( radians(?) )
        * sin( radians(latitude)))) AS distance",
        [$requestedCords['latitude'], $requestedCords['longitude'], $requestedCords['latitude']]
    )
    ->having("distance", "<=", $requestedCords['radius'])
    ->orderBy("distance",'asc')
    ->offset(0)
    ->limit(20)
    ->get();

The owner, company_info and the address columns are references to other tables.

Or do I have to get the relations like this and add the query to it or something? And if so, how can I add the query to this? I am a bit confused using queries in laravel

return Company::with(
            'owner',
            'address',
            'companyInfo'
        )->get();

Hope you guys can help me.

Thanks in advance

0 likes
1 reply
SilenceBringer's avatar

@moemenh_ for sure eager loading will be the best solution here

$companies = Company::with(
            'owner',
            'address',
            'companyInfo'
        )
    ->selectRaw(
        "id, owner, company_info, address, latitude, longitude,
        (6371 * acos( cos( radians(?))
        * cos( radians(latitude) )
        * cos( radians( longitude ) - radians(?))
        + sin( radians(?) )
        * sin( radians(latitude)))) AS distance",
        [$requestedCords['latitude'], $requestedCords['longitude'], $requestedCords['latitude']]
    )
    ->having("distance", "<=", $requestedCords['radius'])
    ->orderBy("distance",'asc')
    ->offset(0)
    ->limit(20)
    ->get();

Please or to participate in this conversation.