Skip to main content
Back to packages
447 GitHub stars

mehdi-fathi/eloquent-filter

View on GitHub

Description

Eloquent Filter adds custom filters automatically to your Eloquent Models in Laravel.

A simple implementation without Eloquent Filter

The Resource URI would look like:

/users/index?age_more_than=25&gender=male&created_at=25-09-2019

And a simple implementation in the Controller would look like :

<?php
 
namespace App\Http\Controllers;
 
use App\User;
use Illuminate\Http\Request;
 
class UserController extends Controller
{
public function index(Request $request)
{
$users = User::where('is_active', true);
 
if ($request->has('age_more_than')) {
$users->where('age', '>', $request->age_more_than);
}
 
if ($request->has('gender')) {
$users->where('gender', $request->gender);
}
 
if ($request->has('created_at')) {
$users->where('created_at','>=', $request->created_at);
}
 
return json_encode($users->get());
}
}

This solution is simple and that works well but not for an enterprise project. But you'd have to add a condition for each filter you need. Especially if you would make more complex filtering, your code can become a monster quickly! :boom:

Hence, Eloquent Filter is ready for to you get rid of complexity in addition to saving time.

A simple implementation with Eloquent Filter

Eloquent Filter can help you to manage these features. Just you will set query string to work with that. It would make your own query automatically and systematically while you can control them.

Right after installing Eloquent Filter, the request URI would be like this:

/users/list?age_more_than[operator]=>&age[value]=35&gender=male&created_at[operator]==>&created_at[value]=25-09-2019

And in the Controller, You just need that one line:

/**
* Class UsersController.
*/
 
namespace App\Http\Controllers;
 
use App\User;
 
class UsersController
{
public function list()
{
return User::filter()->get();
}
}

By Eloquent filter implementation, you can use all the documented filters!

Recent Courses on Laravel Daily

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.