Thursday 7 January 2016

To preview the executing or last Query Log in Controllers or Models in Laravel 5

To view/preview the executing query or last executed Query Log in Laravel 5 (including Laravel 4.2, Laravel 5.0, Laravel 5.2), please add the below code and run it.
 
// This is the Sample Controller
class SampleController extends Controller
{
 public function sampleControllerFunction()
 {
  $this->owner_id = 5;
  
  // Enable the Laravel Database Query Log
  DB::enableQueryLog(); 
  
  // Run your Query here
  $item = SampleModel::where('owner_id', $this->owner_id)->first();
  SampleModel::where('owner_id', $owner_id)->forceDelete();

  // Fetch and Print the Last Database Query Log
  print_r( DB::getQueryLog() ); 
 }
}

// This is the Sample Model
class SampleModel extends Model
{
 /**
     * The database table used by the model (mysql).
     *
     * @var string
     */
 protected $table = 'owner_list';

    /**
     * The attributes that are mass assignable..
     *
     * @var string
     */
    protected $fillable = ['id', 'owner_id'];
 
 public function getItemsList()
 {
  // Enable the Laravel Database Query Log
  DB::enableQueryLog(); 

  // Run your Query here
  $item = static::where('owner_id', $this->owner_id)->first();

  // Fetch and Print the Last Database Query Log
  print_r( DB::getQueryLog() ); 
 }
 
}


Please comment me if you have any queries


No comments:

Post a Comment

Please post any queries and comments here.