Skip to content

In Laravel, it is convenient to write the query filter related to the model in a separate class

License

Notifications You must be signed in to change notification settings

Odilbukh/laravel-query-filter

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Laravel Query Filter

In Laravel, it is convenient to write the query filter related to the model in a separate class!

Installation

composer require oooiik/laravel-query-filter

Usage:

for single use

User::filter($validated)->get();

or create a filter

$userFilter = User::createFilter(UserFilter::class);

get a query using a filter

$userFilter->apply($validated)->query();

write filter on filter and get a query

$userFilter->apply($validated);
$userFilter->apply($validated_2)->query();

filter cleaning and reuse

$userFilter->resetApply($validated_3)->query();

In order to use a filter you have to create a new one by the command that is provided by the package:

php artisan make:filter UserFilter

This command will create a directory Filters and UserFilter class inside. To use the filter method of User model use the Filterable trait:

<?php

namespace App\Models;

use Oooiik\LaravelQueryFilter\Traits\Model\Filterable;

class User extends Model
{
    use Filterable;

And set the defaultFilter of a model by adding:

protected $defaultFilter = UserFilter::class;

You can create a custom query by creating a new function in the Filter class, for example filtering books by publishing date:

public function username($username)
{
    $this->builder->where('username', $username);
}
// $validated = ['username' => 'name']

or filter by relationship:

public function role($role)
{
    $this->builder->whereHas('role', function($query) use ($role) {
        $query->where('title', $role);
    })
}
// $validated = ['role' => 'admin']

About

In Laravel, it is convenient to write the query filter related to the model in a separate class

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • PHP 100.0%