ahmedwaleed/laravel-query-filter

1.0.0 2020-04-16 16:50 UTC

README

This package allows you add addional queries to your eloquent model from request params (filters).

Installation

You can install the package via composer:

composer require ahmedwaleed/laravel-query-filter

Basic usage

Create dedicated query scope class by running following command.

php artisan make:query ScopeActiveUsersQuery
// app/Queries/ScopeActiveUsersQuery.php

namespace App\Queries;

use AhmedWaleed\QueryFilter\QueryScope;

class ScopeActiveUsersQuery extends QueryScope
{
    /**
     * Add query to applicable model
     *
     * @param \Illuminate\Database\Eloquent\Builder $builder
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function apply($builder)
    {
        //

        return $builder;
    }
}

Now you need to use QueryScopes trait inside your model on which you want to add addional queries.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use AhmedWaleed\QueryFilter\QueryScopes;

class User extends Model
{
  use QueryScopes;
  
  //
}

Inside your controller method you can add query like so

//..
public function index()
{
  $users = User::addQuery(
    (new ScopeActiveUsersQuery())->when(request()->has('active'))
  )->get();
  
  return view('users.index', compact('users'));
}
//..

add multipple queries:

$users = User::addQuery(
    (new ScopeActiveUsersQuery())->when(request()->has('active'))
)->addQuery(
    (new ScopeUsersLocationQuery())->when(request()->has('location'))
)->get();

::when($condition) method is optional you can skipe if you always want to execute query:

$users = User::addQuery(new ScopeActiveUsersQuery())->get();

you can pass addional data required for query through constructor:

// controller
$data = ['limit' => 10, 'status' => request('active')];

$users = User::addQuery(new ScopeActiveUsersQuery($data))->get();
// App\Queries\ScopeActiveUsersQuery.php

namespace App\Queries;

use AhmedWaleed\QueryFilter\QueryScope;

class ScopeActiveUsersQuery extends QueryScope
{
    /**
     * Add query to applicable model
     *
     * @param \Illuminate\Database\Eloquent\Builder $builder
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function apply($builder)
    {
        $builder->whereStatus($this->data['status'] ?? 1)
          ->limit($this->data['limit'] ?? 50);

        return $builder;
    }
}

A cooler usage

For small query scope like above it maybe overkill but think what if you have a huge queries and request filters either it will grow your model or controller, this package is also apply single responsiblty principle so for every scope you have dedicated class and in future it will also be easy to maintane single query instead of parsing a big query with request filters.

License

The package is License under (MIT).