Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/mykeels/laravel-filters

A laravel package that provides a composable interface for data filtering with query strings 😍
https://github.com/mykeels/laravel-filters

composable eloquent filters

Last synced: about 2 months ago
JSON representation

A laravel package that provides a composable interface for data filtering with query strings 😍

Awesome Lists containing this project

README

        

# Laravel Filters

Imagine that ...

## Filter with Query String

This URL:

```text
/users?name=myk&age=21&company=rick-and-morty&sort_age=desc
```

automatically knew to filter the DB query by responding with users that have their

- name containing `myk`
- age as `21`
- company name containing `rick-and-morty`

and order the records by age in descending order, all without you having to write boilerplate code 😱.

## Load Relationships

Or that you could automatically include a relationship for a model by adding a `?with_relationship` to the URL 😍, like:

![laravel-filters](https://user-images.githubusercontent.com/11996508/43687436-08f61c1c-98cd-11e8-962b-cd32c2d3bfb3.gif)

Hold your horses 😜, I'm about to show you how.

## Setup

- Run `composer require mykeels/laravel-filters` in your terminal to pull the package in.

## Usage

- In the Model class you wish to make filterable, use the `FilterableTrait` like:

```php
builder->where('users.name', 'LIKE', "%$term%");
}

public function company($term) {
return $this->builder->whereHas('company', function ($query) use ($term) {
return $query->where('name', 'LIKE', "%$term%");
});
}

public function age($term) {
$year = Carbon::now()->subYear($age)->format('Y');
return $this->builder->where('dob', '>=', "$year-01-01")->where('dob', '<=', "$year-12-31");
}

public function sort_age($type = null) {
return $this->builder->orderBy('dob', (!$type || $type == 'asc') ? 'desc' : 'asc');
}
}
```

> Note how the name of each method maps to the key of each query string in `/users?name=myk&age=21&company=rick-and-morty&sort_age=desc`, and the parameters of the methods map to the values.

- Inject `UserFilters` in your controller 😍, like:

```php
get();
}
}
```

That's all! 💃

Now, you can execute your app, and use variations of the query strings that your filters allow for. 🔥🔥🔥