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

GodziLaravel's avatar

Is it possible to print out the eloquent query ?

Hello

Is it possible to display the eloquent query like we do with the raw SQL (->tosql())?

I ask this question because my eloquent request is dynamic and I build it by using many other classes

Thanks

0 likes
7 replies
GodziLaravel's avatar

@tykus to display it on the controller :

In fact this eloquent query has a specific join that I want to modify it .

I'm thinking to get the final eloquent request then make my modification and use it !

(...)
        dd($employeeList->toSql()); // here I can see the final raw sql 
        
        $employeeList = $employeeList->paginate($limit);

        return response()->json([
            "employeeList" => $employeeList
        ], 200);
tykus's avatar

@GodziLaravel I am not sure I follow... if you display it in the Controller using dd, then code execution dies? You can register a listen on the DB class before executing the query so the pagination limits and offsets are included.

\DB::listen(fn ($query) => dd([$query->sql, $query->bindings]));
$employeeList = $employeeList->paginate($limit);

And what do you mean to modify a specific join; can't you just modify the Eloquent query? Maybe you need to share the full Eloquent query and explain what you want to modify and why?

1 like
Snapey's avatar

@GodziLaravel replicate the query and then modify it.

Don't try to manipulate a query that has already been built.

jlrdw's avatar

Seems you could normalize data some and drastically cut down (refactor) such a large query.

1 like

Please or to participate in this conversation.