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

grozavule's avatar

What is the Eloquent equivalent of this Query Builder query?

I'm trying to switch from Query Builder to Eloquent models. How can I make my model, VisualLogin, return the last activity per user id and machine id?

Here is my Query Builder equivalent:

$visualLogins = DB::connection('vmfg')
            ->table('LOGINS')
            ->select('USER_ID', 'MACHINE_ID', DB::raw('MAX(LAST_ACTIVITY) as LAST_ACTIVITY'))
            ->groupBy('USER_ID', 'MACHINE_ID')
            ->get();
0 likes
4 replies
MichalOravec's avatar

You can't do more.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class VisualLogin extends Model
{
    /**
     * The connection name for the model.
     *
     * @var string
     */
    protected $connection = 'vmfg';
}
$visualLogins = VisualLogin::selectRaw('user_id, machine_id, max(last_activity) as last_activity')
    ->groupBy('user_id', 'machine_id')
    ->get();
jlrdw's avatar
jlrdw
Best Answer
Level 75

Same except:

Logins::

In a raw you need to bind parameters, or it's unsafe.

I would put only the aggregate in raw, just example:

$quy = Powner::query()->leftJoin('dc_pets', 'dc_powners.ownerid', '=', 'dc_pets.ownerid')
                ->select('dc_powners.ownerid', 'dc_powners.oname')
                ->selectRaw('count(dc_pets.petid) as countOfPets')   // here
                ->groupby('dc_powners.ownerid')
                ->orderby('dc_powners.oname')
                ->get();
grozavule's avatar

Thanks for your help. Here is my final result based on your suggestion:

VisualLogin::select('USER_ID', 'MACHINE_ID')
                ->selectRaw('MAX(LAST_ACTIVITY) as LAST_ACTIVITY')
                ->groupBy('USER_ID', 'MACHINE_ID')
                ->get()

Please or to participate in this conversation.