How to view latest SQL statement excuted in Laravel

To view the latest sql query executed in Laravel you can

DB::enableQueryLog();

print_r(DB::getQueryLog());

Note that you have to enable the query log before executing the query and view/print it after execution ..

A good practice is to enable it only in Local environment

if (App::environment('local')) {
    // The environment is local
    DB::enableQueryLog();
}

 

How to sanitize raw data in Laravel

When doing a raw data query from user input like this:

$someVariable = Input::get("some_variable");

$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = '$someVariable'") );

we are at risk of SQL injection , to avoid that we can bin parameters to our query like this:

$someVariable = Input::get("some_variable");

$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = :somevariable"), array(
   'somevariable' => $someVariable,
 ));

 

Another point is that if we want to do a raw that doesn’t return a value, we can do it like this

DB::statement( 'ALTER TABLE HS_Request AUTO_INCREMENT=1111' );

and that way can take parameters as well

DB::statement( 'ALTER TABLE HS_Request AUTO_INCREMENT=:incrementStart', array('incrementStart' => 1111) );

 

How to measure timing in Laravel using debugbar

If you want to measure the timing of some code in Laravel , you can use debugbar measure function

Debugbar::startMeasure('start');

Debugbar::stopMeasure('stop');

but if, for any reason, you can’t use debugbar, you can go back to pure php and use this code

 $start = microtime(true);
 
 $time_elapsed_secs = microtime(true) - $start;

 

How to test sending Laravel email from command prompt

If you want to test if you can send email from Laravel using only command prompt, here is how ..

  • First open your favorite command prompt
  • Go to your root folder of your website (i.e cd c:\xampp\htdocs\mySite )
  • Run this command: php artisan tinker
  • Mail::send(‘myView‘, [], function ($message) { $message->to(‘yourEmail@test.com’)->subject(‘Sending mail is OK’); });