Laravel 5.1 Eager Loading Cannot do additional where

I don't know what i'm doing wrong here but this code

$models = Model::with(['relationship' => function ($query) {
        $query->whereBetween('date', [$this->today->copy()->startOfDay(), $this->today->copy()->endOfDay()]);
    }])->where('status', 'active')->where('position', '!=', 'dev')->where('status', '=', 'good')->get();

doesn't work as expected. It does eager load the relationship it exists in the object but the problem is I cant do something like this

foreach($models as $model)
    {
        echo $model->relationship->where('status', '=', 'somestatus')->count() . '<br>';
    }

it returns 0 but when I check in collection it is not 0. Do you guys know why does this code not work? Thank you guys.

Upvotes: 0

Views: 43

Answers (1)

DevK
DevK

Reputation: 9962

You need to remove '=' (middle parameter) from your ->relationship->where('status', 'somestatus'). Since you're doing it on a collection it only takes 2 parameters.

So like this:

foreach($models as $model)
{
    echo $model->relationship->where('status', 'somestatus')->count() . '<br>';
}

Upvotes: 1

Related Questions