Suraj
Suraj

Reputation: 2277

How to attach conditionals to eloquent relation query?

I am trying to create the filters and I just want to attach the query to relation by using some conditionals. I don't want to put those conditional in the first block of the code. So how can I get the query instance so I can attach the new queries to the existing relation?

    $query = Category::query();

    $query->where('category_type', 'xyz')
        ->with(['products' => function ($query) {
            $query->where('condition1', 'value')
                ->where('condition2', 'value');
        }]);


    if (isset($queryParams['param1'])) {
        $query->with(['products' => function ($query) use ($queryParams) {
            $query->getQuery()->where('type', $queryParams['param1']);
        }]);
    }

Currently, it just overwrites the first query relation condition.

Upvotes: 0

Views: 59

Answers (1)

akshaypjoshi
akshaypjoshi

Reputation: 1295

This should work :

$query = Category::query();

$query->where('category_type', 'xyz')
->with(['products' => function ($query) use ($queryParams) {
    $query->where('condition1', 'value')
    ->where('condition2', 'value');
    if (isset($queryParams['param1'])) {
        $query->where('type', $queryParams['param1']);
    }
}]);

Upvotes: 1

Related Questions