Tucker-Eric / EloquentFilter

An Eloquent Way To Filter Laravel Models And Their Relationships
http://tucker-eric.github.io/EloquentFilter
MIT License
1.72k stars 120 forks source link

Need help! #124

Closed tinkeshwar closed 4 years ago

tinkeshwar commented 4 years ago

$students = \App\Models\Student::active() ->with(['transactions.fees' => function($fees) use($session) { $fees->where('session_id', $session); }]) ->whereHas('admissions', function($admission) use($session) { $admission->where('session_id', $session); }) ->sortable() ->paginate(30);

I am using the above query to get the result, now I want to add a filter of student name, my question is how can I create a filter with this library that can give me result based on above conditions?

Tucker-Eric commented 4 years ago

The filter method is part of the query builder so you can just add it to your query already.

Create the filter class App\ModelFilters\StudentFilter in app/ModelFilters/StudentFilter.php and then apply the EloquentFilter\Filterable; trait to your Student model. Then your query can add the filter method:

$students = \App\Models\Student::active()
    ->with(['transactions.fees' => function($fees) use($session) {
        $fees->where('session_id', $session);
    }])
    ->whereHas('admissions', function($admission) use($session) {
        $admission->where('session_id', $session);
    })
    ->filter($request->all()) // where $request->all() returns ['name' => 'some-name']
    ->sortable()
    ->paginate(30);

Then the filter could look something along the lines of:

class StudentFilter extends ModelFilter
{
    public function name($name)
    {
         $this->where('name', $name');
    }
}