Showing posts with label queries. Show all posts
Showing posts with label queries. Show all posts

Thursday, July 6, 2017

Laravel 5: Logging All DB Query | Log Queries | Listen Query Events | Query Logging | Sql Logging | Log SQL | DB Connection Class | Laravel Database Connection | Laravel DB Connection Query Run Method

Laravel 5: Logging All DB Query | Log Queries | Listen Query Events | Query Logging | Sql Logging | Log SQL | DB Connection Class | Laravel Database Connection | Laravel DB Connection Query Run Method.

Logging query in Laravel is easy. You can then register event listener for DB. At first you need to create an service provider in directory ("project/app/Providers" ) named QueryLogProvider with following contents:


<?php
namespace App\Providers;

use Monolog\Logger;
use Illuminate\Support\Facades\DB;
use Monolog\Handler\StreamHandler;
use Illuminate\Support\ServiceProvider;

class QueryLogProvider extends ServiceProvider
{
    public function register()
    {
        DB::listen(function ($query) {
            $logFile = storage_path('logs/query-log-'.date("Y-m-d").'.log');
            $stream = new Logger('log');
            $stream->pushHandler(new StreamHandler($logFile));
            $bindings = $query->bindings;
            $time = $query->time;
            $stream->info($query->sql, compact('bindings', 'time'));
        });
    }
}

You are done with creating provider. Now you have to register in file "project/config/app.php" in section 


'providers' => [
    .....,
    App\Providers\QueryLogProvider::class
],

All your queries will be stored on the location "project/storage/logs" with prefix file name "query-log".

But you can do some wired things, editing source code. To do so first need to open your connection class:

Illuminate\Database\Connection

and navigate to function:

protected function run($query, $bindings, Closure $callback)

actually all query in Laravel passed through this method.

So you can do whatever you wish to do here.

Saturday, February 11, 2017

Laravel join or left join queries AS different name

There are many situations where you need to join same table, but must have different names (you can define this as alias). Below is a simple code snippet to show how you can join same table with different name.

$limit = 10;
$page = 1;
$groups = DB::table('person')
       ->leftJoin('users as for_user', function ($join) {
           $join->on('for_user.id', '=', 'person.for_id')->where("for_user.id", "=", 10);
       })
       ->join('users as by_user', function ($join) {
           $join->on('by_user.id', '=', 'person.by_id');
       })
       ->where('person.status', '=', 1)
       ->select('person.id', 'person.first_name', 'by_user.first_name')
       ->limit($limit)->offset($page * $limit)
       ->get();