PHP code example of caue-santos / laravel-model-utils

1. Go to this page and download the library: Download caue-santos/laravel-model-utils 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/ */

    

caue-santos / laravel-model-utils example snippets


use CaueSantos\LaravelModelUtils\ModelHelpers;

$query = User::query();
ModelHelpers::loadRelationWithJoin($query, 'company.industry', function ($join, $relatedAlias) {
    $join->where("{$relatedAlias}.active", true);
}, 'left');

ModelHelpers::whereHasRelationWithJoin($query, 'posts.tags', function ($subQuery, $lastAlias) {
    $subQuery->where("{$lastAlias}.name", 'featured');
});

use CaueSantos\LaravelModelUtils\Traits\HasWithAggregatesRelation;

class Company extends Model
{
    use HasWithAggregatesRelation;
}

Company::query()
    ->withNestedCount('users.posts as total_posts')
    ->withNestedSum('users.posts as total_likes', 'likes_count')
    ->withNestedAvg('users as avg_age', 'age', function ($subQuery, $finalAlias) {
        $subQuery->where("{$finalAlias}.active", true);
    })
    ->get();

Company::query()->withNestedCount([
    'users.posts as total_posts',
    'users.posts.comments as total_comments' => fn ($q) => $q->where('approved', true),
]);

use CaueSantos\LaravelModelUtils\Traits\RelationshipsTrait;

class Post extends Model
{
    use RelationshipsTrait;
}

$post = new Post;
$post->relationships();
// [
//     'author' => [
//         'name' => 'author', 'type' => 'BelongsTo', 'typeQualified' => BelongsTo::class,
//         'model' => User::class, 'table' => 'users', 'primary' => 'id',
//         'foreign_key' => 'user_id', 'local_key' => null, 'pivot' => [], 'through' => [],
//         'computed' => ['full_name' => 'getFullNameAttribute'],
//     ],
//     ...
// ]