Showing posts with label laravel. Show all posts
Showing posts with label laravel. Show all posts

Laravel: Debug by Printing Eloquent Query

Use ->toSql() method like shown below to get the SQL

<?php
use Log;

$name = "hawk";

$userResults = DB::table('users')
       ->leftJoin('planets', function($join) {
         $join->on('users.planet_id', '=' , 'planets.id');
        })
       ->where('users.lname' , 'like', '%'.$name.'%');

//You can print the SQL in your log file
Log::info('My search sql: '.($userResults->toSql()));

// OR you can save into a string variable
$mySQL = $userResults->toSql();

//Then use your get function
$userResults = $userResults->get(array('users.fname', 'planets.name'));
?>

The above code will print the following into your /storage/logs/laravel.log file

[2014-09-30 17:58:07] production.INFO: My search sql: SELECT * FROM  users LEFT JOIN planets ON (users.planet_id = planets.id) WHERE users.lname LIKE '%hawk%' 

Laravel, Eloquent: SQL query with left join

If the query needs parentheses/brackets for a where condition like below Normal SQL:

SELECT users.fname, planets.name 
FROM  users
LEFT JOIN  planets ON (users.planet_id = planets.id)
WHERE users.lname LIKE '%hawk%' 

ELOQUENT SQL:

$name = "hawk";

$userResults = DB::table('users')
       ->leftJoin('planets', function($join) {
         $join->on('users.planet_id', '=' , 'planets.id');
        })
       ->where('users.lname' , 'like', '%'.$name.'%')
       ->get(array('users.fname', 'planets.name'));

Eloquent: SQL Query with where or in brackets

If the query needs parentheses/brackets for a where condition like below Normal SQL:

SELECT * 
FROM  users
WHERE planet = 'earth'
AND (fname LIKE '%hawk%' OR lname LIKE '%hawk%')
AND state = 'FL'

ELOQUENT SQL:

$name = "hawk";

$usersResults = DB::table('users')
    ->where('planet', '=', 'earth')
    ->where(function($query) use ($name){
            $query->where('fname' , 'like', '%'.$name.'%');
            $query->orWhere('lname' , 'like', '%'.$name.'%');
      })
     ->where('state', '=', 'FL')
    ->get();

Python contextlib for Timing Python code

If you've ever found yourself needing to measure the execution time of specific portions of your Python code, the `contextlib` module o...