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

JavedBaloch's avatar

Convert SQL raw query to Laravel ORM or Query Builder

Hi - I have some raw queries I'm getting stuck while converting them into Laravel query builder or in ORM. If someone can please convert them thank you.

Today : select distinct id, ip_address, browser from table_name where DATE(visited_time) = CURDATE();

Month : select distinct id, ip_address, browser from table_name where month(visited_time) = month(NOW()) and year(visited_time) = year(NOW());

Week : select distinct id, ip_address, browser from table_name where week(visited_time) = week(NOW()) and year(visited_time) = year(NOW());

Year : select distinct id, ip_address, browser from table_name where year(visited_time) = year(NOW());

0 likes
3 replies
EmilMoe's avatar

I'm supposing that you are using this for a log?

use App\Logger;
use Carbon\Carbon;

[..]

$log = Logger::whereDay('visited_time', Carbon::now()->day)
    ->whereMonth('visited_time', Carbon::now()->month)
    ->whereYear('visited_time', Carbon::now()->year)
    ->get();

$log->first()->browser;

What you mean about distinct id I'm not sure, isn't that always distinct?

1 like
VimKanzo's avatar

Hello @emilmoe can you please help me convert this raw query to eloquent?

$data = DB::select("select

            to_char(submit_date, 'YYYY-MM-DD') AS sent_at,

            status as stat,

            count(username) as t

            from logs

            where username=?

            and (submit_date between (LOCALTIMESTAMP - INTERVAL '6 DAYS')  and (LOCALTIMESTAMP))

            GROUP BY sent_at,stat

            ORDER BY sent_at", [$this->currentUser()->username]);

Thanks

Tray2's avatar

Why not open your own thread for this instead of using one that is a year old.

1 like

Please or to participate in this conversation.