PHP code example of kobykorman / eloquentify

1. Go to this page and download the library: Download kobykorman/eloquentify library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kobykorman / eloquentify example snippets


use Illuminate\Database\Eloquent\Model as BaseModel;
use KobyKorman\Eloquentify\EloquentifiesQueries;

class Model extends BaseModel
{
    use EloquentifiesQueries;
}

// PostgreSQL
$result = DB::select("
    SELECT users.id, users.name, users.email,

        (SELECT json_build_object('id', profiles.id, 'bio', profiles.bio)
         FROM profiles WHERE profiles.user_id = users.id) AS profile,

        (SELECT json_agg(json_build_object(
            'id', roles.id, 'name', roles.name,

            'permissions', (SELECT json_agg(json_build_object('id', permissions.id, 'name', permissions.name))
                            FROM permissions
                            JOIN permission_role ON permission_role.permission_id = permissions.id
                            WHERE permission_role.role_id = roles.id)
        ))
        FROM roles
        JOIN role_user ON role_user.role_id = roles.id
        WHERE role_user.user_id = users.id) AS roles

    FROM users
    WHERE users.id = ?
", [$id]);

$user = User::eloquentify($result)->first();

$user->profile->bio;                          // hydrated HasOne
$user->roles->first()->permissions;           // nested collections, any depth
$user->roles->first()->name = 'Admin';
$user->roles->first()->save();                // they are real models

$post->tags->first()->pivot->created_at; // works exactly like native eager loading