Friday, June 30, 2017

Laravel 5: Change Default Database connection Dynamically | Change database name of connection on the fly | How to change default database connection in controller | Multiple DB Connections | Specifying DB connection information dynamically instead of config key | How to Use Multiple Database Connections in Laravel Application

use Illuminate\Config\Repository;

public function __construct(Repository $config) {}


So now you can $config from the above reference.

Below is a sample usage of change database name:

$config->set("database.connections.mysql.database", "test");

or

app()->config->set("database.connections.mysql.database", "test");

You can use this functionality in middle-ware.

If your app already connected then you have to disconnect it before make new connection available.

Below follow steps to disconnect connection:

$dm = app("Illuminate\\Database\\DatabaseManager");

$dm->disconnect();

Laravel 5: How to set and get config variable in Controller | Use of Application Config in Controller

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Config\Repository;

public function __construct(Application $app, Repository $config) {}

So now you can $app and $config from the above reference.

Below is a sample usage of $config:

$config->set("database.connections.mysql.database", "test");

How to select two additional columns from another table based on values in the base table

Below is sample SQL showing how we can use additional columns from another table based on value of base table.


SELECT base_table.id, another_table.id AS some_other_name, another_table.name
FROM base_table AS base_table
  INNER JOIN (SELECT id, name FROM another_table) another_table
    ON base_table.another_table_id = another_table.id
WHERE another_table.some_reference = 15
ORDER BY base_table.id DESC
LIMIT 10


Laravel 5: Fluent Query Builder Join with subquery

Laravel is a strong php based framework today. Below is a code sample showing how raw query used for join.

$list = DB::table("users AS u")
    ->join(DB::raw('(SELECT id AS oid,name FROM organization) o'), function($join) {
        $join->on('o.oid', '=', 'u.organization_id');
    })
    ->where("o.oid", 15)
    ->limit(10)
    ->orderBy("u.id", "DESC")
    ->select("u.id", "o.oid", "o.name")
    ->get();


Thursday, June 29, 2017

How create json format with group-concat mysql | How to put JSON into a column data if sub-query returns more than 1 row in MySQL | Optimized way of getting subqueries at once using JSON

How create json format with group-concat mysql |  How to put JSON into a column data if sub-query returns more than 1 row in MySQL | Optimized way of getting subqueries at once using JSON.

A bit convoluted, but you could create JSON objects for each row, concatenate them using GROUP_CONCAT and cast the result (wrapped in [] to make it an array) to JSON;

Below is the full example:


<?php
define("DB_DEFAULT_HOST", "localhost");
define("DB_DEFAULT_DATABASE", "test71");
define("DB_DEFAULT_USER", "root");
define("DB_DEFAULT_PASSWORD", "");

$dbh = null;
try {
    $dbh = new PDO(
        "mysql:host=" . DB_DEFAULT_HOST . ";dbname=" . DB_DEFAULT_DATABASE,
        DB_DEFAULT_USER,
        DB_DEFAULT_PASSWORD
    );
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->beginTransaction();

    $query =
        "SELECT
            s.name AS Name, s.roll AS Roll,
            CONCAT(
              '[', COALESCE(
                GROUP_CONCAT(
                  CONCAT('{', 
                    '\"ExamName\":', '\"', HEX(CONVERT(e.subject USING utf32)), '\"',
                    ',\"Score\":', '\"', e.score, '\"',
                  '}')
                  SEPARATOR ','
                ), ''
              ), ']'
            ) AS ExamsRaw
        
        FROM student AS s
          LEFT JOIN exams AS e ON e.student_id=s.id
        
        GROUP BY s.id";

    $students = $dbh->query($query)->fetchAll(PDO::FETCH_OBJ);
    foreach ($students as $entity) {
        $entity->Exams = array();
        foreach (json_decode($entity->ExamsRaw) as $group) {
            $group->ExamName = hexToStr($group->ExamName);
            array_push($entity->Exams, $group);
        }
        unset($entity->ExamsRaw);
    }
    echo "<pre>";
    print_r($students);
    echo "</pre>";
}
catch (\Exception $ex) {
    echo "MySQL_Error=" . $ex->getMessage();
    $dbh->rollBack();
}

function hexToStr($hex)
{
    $string = '';
    for ($index = 0; $index < strlen($hex) - 1; $index += 2) {
        $string .= chr(hexdec($hex[$index] . $hex[$index + 1]));
    }
    return $string;
}

And below is the output of above example code block:


Array
(
    [0] => stdClass Object
        (
            [Name] => Prtiom First Year
            [Roll] => P1
            [Exams] => Array
                (
                    [0] => stdClass Object
                        (
                            [ExamName] => ©|æ|þ|½|±|®|¶
                            [Score] => 1.12
                        )

                    [1] => stdClass Object
                        (
                            [ExamName] => Subject 2   
                            [Score] => 2.54
                        )

                    [2] => stdClass Object
                        (
                            [ExamName] =>  ¡¢£¤¥¦§¨©
                            [Score] => 1.98
                        )

                )

        )

    [1] => stdClass Object
        (
            [Name] => Pritom Second Year
            [Roll] => P2
            [Exams] => Array
                (
                    [0] => stdClass Object
                        (
                            [ExamName] => Subject 2
                            [Score] => 4.00
                        )

                    [1] => stdClass Object
                        (
                            [ExamName] => Subject 3
                            [Score] => 3.00
                        )

                )

        )

)

Aware that mysql group function max length is by default 1024 characters. If your group function more than 1024 then you have to change limit of mysql group function using following query:

This is for current session:
SET SESSION group_concat_max_len = 1000000;

But if you want it global scope, then do following:
SET GLOBAL group_concat_max_len = 1000000;

Tuesday, June 27, 2017

Laravel 5: How to modify Request values | How to "artificially" add values to Request array | How to dynamically add params to Request array

Laravel 5: How to modify Request values | How to "artificially" add values to Request array | How to dynamically add params to Request array. You can use the merge() method on the $request object. In spite of the methods name, it actually replaces any values associated with the member names specified by the keys of the parameter rather than concatenating their values or anything like that. 

A few times I encountered a situation – a store() or update() method with Request parameter, but I needed to add some additional value to the request before calling Eloquent functions. So how to do that? Apparently, pretty easy.

use Illuminate\Http\Request;

protected $request;

public function __construct(Request $request)
{
    $this->request = $request;

}

$this->request->merge(["custom" => "New Custom Value"]);






..

Monday, June 26, 2017

Validating a URL in PHP

Check if the variable $url is a valid URL:

The FILTER_VALIDATE_URL filter validates a URL.

Possible  flags:

FILTER_FLAG_SCHEME_REQUIRED - URL must be RFC compliant.
Like http://example

FILTER_FLAG_HOST_REQUIRED - URL must include host name.
Like http://www.example.com

FILTER_FLAG_PATH_REQUIRED - URL must have a path after domain.
Like www.example.com/example1/

FILTER_FLAG_QUERY_REQUIRED - URL must have a query string.
Like "example.php?name=Peter&age=37"

filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED)
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)