#Issue with using wherePivot inside where function

3 messages · Page 1 of 1 (latest)

fallow vale
#

While trying to filter an Eloquent query by a pivot column I'm facing an issue with using wherePivot inside a where function.

The following syntax doesn't work:

use Illuminate\Database\Eloquent\Builder;

$team->users()
      ->when($report === 'status', fn (Builder $users) => $users->wherePivot('has_status_reporting', true))
      ->get();

The following syntax works:


use Illuminate\Database\Eloquent\Builder;

$team->users()
      ->wherePivot('has_status_reporting', true)
      ->get();

I've found the following GitHub issue... but it seemingly was just closed without a solution by the Laravel team: https://github.com/laravel/framework/issues/38728

Is there any solution to this? I guess I might as well just put the query in a variable and add the wherePivot depending on the $status variable "oldschool".

Kind regards!

GitHub

Laravel Version: 8.48 PHP Version: 8.0 Database Driver & Version: PostgreSQL 12.8 Description: There's User model with Role many-to-many relationship: public function roles(): BelongsToMany...

unkempt yoke
#

Looks like a bug to me, not sure why it was marked as solved. Might be worth filing a new issue. In the meantime, you can work around it with php $team->users() ->when($report === 'status', fn (Builder $users) => $users->having('pivot_has_status_reporting', true)) ->get();

fallow vale
#

Hmm interesting, that does give the following exception:
SQLSTATE[ 42S22]: Column not found: 1054 Unknown column 'pivot_has_status_reporting' in 'having clause' (Connection: mysql, SQL: ... )

I currently went with the following:

$query = $team->users()
            ->with([...])
            ->whereActive($date->toDateString());

        $users = match ($report) {
            'whereabouts' => $query
                ->wherePivot('has_whereabouts_reporting', true)
                ->get(),
            'status' => $query
                ->wherePivot('has_status_reporting', true)
                ->get(),
            default => $query->get()
        };

Which seems to work; a bit more lines than I intended, but I guess it works for now.

I'll see if I can make the time to create a new issue later on. 🙂