domenica 26 novembre 2017

Howto preview sql query code generated in Eloquent

The simplest method to show the query generated by Eloquent is by utilizing a ->toSql() method.
We only need to replace the closing ->get() with ->toSql() and then print out the results with dd() or die() funnction.

Here is an example:

    
    $users = DB::table('users')
        ->where('email', 'x@y.xxx')
        ->where('is_active', true)
        ->toSql();
//        ->get();
    dd($users);

This is the output:

"select * from `users` where `name` = ? and `is_active` = ?"

A little more complex and complete way is to enable and use the QueryLog method.

Here the example:

    DB::enableQueryLog();
    $users = DB::table('users')
    ->where('email', 'x@y.xxx')
    ->get();

    dd(DB::getQueryLog());

This is the output:

array:1 [
  0 => array:3 [
    "query" => "select * from `users` where `email` = ?"
    "bindings" => array:1 [
      0 => "x@y.xxx"
    ]
    "time" => 61.13
  ]
]

Nessun commento:

Posta un commento