PHP code example of omalizadeh / laravel-query-filter

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

    

omalizadeh / laravel-query-filter example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Omalizadeh\QueryFilter\Traits\HasFilter;

class User extends Model
{
    use HasFilter;

    public function profile(): HasOne
    {
        return $this->hasOne(Profile::class);
    }

    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }
}



namespace App\Filters;

use Omalizadeh\QueryFilter\ModelFilter;

class UserFilter extends ModelFilter
{
    protected function selectableAttributes(): array
    {
        return [
            'id',
            'phone'
        ];
    }

    protected function sortableAttributes(): array
    {
        return [
            'id',
            'created_at',
            'updated_at'
        ];
    }

    protected function summableAttributes(): array
    {
        return [
            'views'
        ];
    }

    protected function filterableAttributes(): array
    {
        return [
            'id',
            'phone',
            'is_active'
        ];
    }

    protected function filterableRelations(): array
    {
        return [
            'profile' => [
                'gender',
                'first_name'
            ],
            'posts' => [
                'post_body' => 'body'
            ]
        ];
    }

    protected function loadableRelations(): array
    {
        return [
            'profile'
        ];
    }
}


public function index(UserFilter $userFilter)
{
    $userFilterResult = User::filter($userFilter);
    
    // total resources count based on filters
    $count = $userFilterResult->count();
    
    // total sum of given attributes in filter if there is any
    $sums = $userFilterResult->sums();
    
    // Get query results as collection (paginated if there is pagination in filters)
    $users = $userFilterResult->data();
    
    // do stuff and return response
}