Home > OS >  Moving pivot query builder from controller to model scope
Moving pivot query builder from controller to model scope

Time:10-20

I have this working in my controller currently:

use App\Models\Organisation;
use App\Models\User;

public function show(User $user)
{
    $orgs = Organisation::with([
            'users' => function ($query) use ($user) {
                $query->where('user_id', '=', $user->id)
                      ->orWhereNull('user_id');
            }
        ])
        ->get();

    dd($orgs);
}

I would like to move as much as possible to the model using a dynamic local scope. I have tried:

public function scopeAllOrgsOneUserMemberOrNot($query, $user)
{
    $query->where('user_id', '=', $user->id)->orWhereNull('user_id');
}

But when I run:

public function show(User $user)
{
    $orgs = Organisation::with(['users' => function ($query) use ($user) {
        $query->AllOrgsOneUserMemberOrNot($query, $user);
    }])->get();
    dd($orgs);
}

I get back the following ErrorException: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$id

How do I move this query builder snippet to a scope?

CodePudding user response:

The scope's first parameter does not need to be passed. Check the example in the documentation. function scopeActive($query) { ... } turns into active().

$query->AllOrgsOneUserMemberOrNot($user);

This should work.

  • Related