Laravel-datatables: Filter eager loaded relationships

Created on 26 Jan 2019  路  5Comments  路  Source: yajra/laravel-datatables

I have a filter that gets passed with the ajax.data property and in my controller

$model = Timesheet::select('*')->with(['user', 'job']);

        return DataTables::of($model)
        ...
            ->filter(function ($query) {
                if (request()->has('jobFilter') && !empty(request()->jobFilter)) {
                    $query->join('jobs', 'timesheets.job_id', '=', 'jobs.id');
                    $query->where('jobs.id', request('jobFilter'));
                }
            }, true)
        ->make(true);

Which works, but is there a way to just filter on the relationship without doing a join here?

question

Most helpful comment

How did you do it? I think it something like below may work:

$model = Timesheet::select('*')->with(['user', 'job']);

        return DataTables::of($model)
        ...
            ->filter(function ($query) {
                if (request()->has('jobFilter') && !empty(request()->jobFilter)) {
                    $query->whereHas('job', function($query) {
                      $query->where('jobs.id', request('jobFilter'));
                    }
                }
            }, true)
        ->make(true);

All 5 comments

Try using whereHas.

That's no help really. whereHas just returns records where the relationship exists but I need to filter based on properties of the relationship.

How did you do it? I think it something like below may work:

$model = Timesheet::select('*')->with(['user', 'job']);

        return DataTables::of($model)
        ...
            ->filter(function ($query) {
                if (request()->has('jobFilter') && !empty(request()->jobFilter)) {
                    $query->whereHas('job', function($query) {
                      $query->where('jobs.id', request('jobFilter'));
                    }
                }
            }, true)
        ->make(true);

Or you can have a hidden column for job.id for it to be included on search.

```js
columns: [
...,
{name: 'job.id', visible: false}
]

Oh yeah, whereHas with a callback. Dunno why that didn't register in my brain lol. It's right there in the docs too that you linked to. Sometimes you just can't see the wood for the trees.

Works great thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

alejandri picture alejandri  路  3Comments

kamrava picture kamrava  路  3Comments

vipin733 picture vipin733  路  3Comments

ghost picture ghost  路  3Comments

ahmadbadpey picture ahmadbadpey  路  3Comments