PHP code example of yassinedabbous / laravel-dynamic-query

1. Go to this page and download the library: Download yassinedabbous/laravel-dynamic-query 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/ */

    

yassinedabbous / laravel-dynamic-query example snippets


    use HasDynamicFields; // for columns, relations, appends and aggregates
    use HasDynamicFilter; // for filters where, having, joins
    use HasDynamicSorts;  // for sorting results 
    use HasDynamicGroup;  // for grouping results

    # Or just
    use HasDynamicQuery;

class UserController
{
    public function index()
    {
        $result = User::dynamicSelect()       # = SELECT id, name, age, (...) as posts_count ...
                        ->dynamicFilter()       # = WHERE id=x and name like x% ... 
                        ->dynamicOrderBy()      # = ORDER BY id DESC
                        ->dynamicGroupBy()      # = GROUP BY PRICE
                        ->dynamicPaginate();    # = limit 10 offset 0

        $result->dynamicAppend();               # = setAppends for each model
        return $result;

        # Or just
        return User::dynamicQuery();            # call all dynamic features at once
    }
}

class User extends Model
{
    use HasDynamicQuery;

    // Define the list of selectable columns.
    // Only the returned columns can be requested via the API.
    public function dynamicColumns(): array
    {
        return ['id', 'name', 'avatar', 'birthday', 'created_at'];
    }
    
    ...
}

class Post extends Model
{
    ...
    // Define the list of allowed relations.
    // Only these relations can be requested via the API.
    // Specify each relation along with its dependent columns.
    public function dynamicRelations(): array
    {
          return [
            'user' => 'user_id',                                        // "user" relation depends on 'user_id' column
            'commentable' => ['commentable_type', 'commentable_id'],    // "morphable" relation depends on both 'morphable_type' and 'morphable_id' columns
            'replies' => null,                                          // "replies" relation has no dependencies
          ];
    }
    
    ...
}

class User extends Model
{
    ...
    // Define the list of allowed appends.
    // Only these appended fields can be requested via the API.
    // Specify dependencies for each append (columns or relations).
    public function dynamicAppends(): array
    {
        return [
            'status_name'     => 'status',                            // "status_name" depends on 'status' relation
            'full_name'       => ['first_name', 'last_name'],         // "full_name" depends on 'first_name' and 'last_name' columns
            'custom_key',                                             // "custom_key" has no dependencies
        ];
    }
    
    ...
}

class User extends Model
{
    ...
    // Define the list of allowed aggregates.
    // Only the returned aggregates can be requested via the API.
    // Each aggregate field can be a named scope or a closure.
    public function dynamicAggregates(): array
    {
        return [
            'custom_aggr'                => null,                       // Equivalent to ->customAggr() scope
            'another_custom'        => 'second_named_scope',            // Equivalent to ->secondNamedScope() scope
            'employees_count'       => fn($q) => $q->withCount('employees'),
            'employees_sum_salary'  => fn($q) => $q->withSum('employees', 'salary'),
        ];
    }

    // Named scope
    public function scopeCustomAggr($q){
        return $q->withCount('relation', fn($b) => $b->where('c', 'v'));
    }
    
    ...
}

    // List of accepted filters (all operators are applicable).
    public function dynamicFilters(): array {
        return ['name', 'id', 'price'];
    }


    // OR, define specific operators for each filter.
    public function dynamicFilters(): array {
        return [
            'name'    => null,                             // "name" accepts all operators.
            'id'      => '=',                              // "id" accepts only the equality operator "="
            'price'   => ['=', '!=', '<', '<=', '>', '>='],// "price" accepts only 6 comparison operators
        ];
    }

{
    ...
    public function dynamicFilters(): array
    {
        return [
            'with_trashed'          => null,                                 // Equivalent to ->withTrashed() scope
            'custom_filter'         => ['=', '!=', '<', '<=', '>', '>='],    // Equivalent to ->customFilter() scope
        ];
    }

    // named scope
    public function scopeCustomFilter($q){
        return $q->whereHas('relation', fn($b) => $b->where('key', 'value'));
    }
    
    // you can also benefits from params provided by this package
    public function scopeCustomFilter($q, $value, $operator, $logic, $not, $clause){
        return $q->whereHas('relation', fn($b) => $b->where('key', $operator, $value));
    }

    ...
}

    public function dynamicSorts(): array {
        return ['id', 'price', ];
    }

    public function dynamicGroups(): array {
        return ['status', 'month', ''];
    }

class UserController
{
    public function index()
    {
        $result = User::dynamicPaginate(maxPerPage: 30, allowGet: true);
    }
}



return [
    /**configuration would be here */
];
diff
-    public function posts()
+    public function posts(): Relation
    {
        $this->hasMany(Post::class);
    }
diff
- api/data?price=1000&title=product&with_items=true&has_reviews=true
+ api/data?price=1000&title=product&reviews=1&sort=-id&per_page=7&_fields=id,name,discount_amount,active_items:id|name

- $query = Model::query();
- if($request->filled('price')){
-     $query->where('price', $query->price);
- }
- if($request->filled('price')){
-     $query->where('price', 'like', "{$query->price}%");
- }
- if($request->has('with_active_items') && $request->with_active_items){
-     $query->with('items', function($q){
-         $q->where('active', 1)->select('id', 'name');
-     });
- }
- if($request->filled('has_reviews')){
-     $query->withCount('reviews', function($q){
-         $q->where('rate', '>=', 1);
-     });
-     $query->having('reviews_count', '>=', 1);
- }
- 
- $query->select('id', 'title', 'price', 'discount');
- 
- $query->orderBy('id', 'desc');
- 
- $results = $query->paginate(7);
- 
- foreach($results as $value){
-     $value->setAppends(['discount_amount']);
-     $value->setVisible(['id', 'name', 'discount_amount']);
- }
- 
- return $results;
+ return Model::dynamicQuery();