abkrim
4 months ago
759
4
Nova

Nova indexQuery in relationships of relationship

Posted 4 months ago by abkrim

I've 3 models

User has a hasmany relation (domains()) with Domain and this hasMany relation (mailboxes) with Mailbox

User.php

public function domains()
{
    return $this->hasMany(Domain::class);
}

Domain.php

public function user()
{
    return $this->belongsTo(User::class);
}

public function mailboxes()
{
    return $this->hasMany(Mailbox::class, 'domain', 'domain');
}

Mailbox.php

public function domains()
{
    return $this->belongsTo('App\Domain', 'domain', 'domain');
}

Code below work fine for get only mailboxes owned but if put in policies not work.

public function view(User $user, Mailbox $mailbox)
{
    $domains = Domain::where('user_id', $user->id)->pluck('domain')->toArray();

    return User::with([
        'domains.mailboxes' => function ($builder) use ($domains) {
            $builder->where('domain',$domains);
        }
    ])->find($user);

}

I tried overrinding indexQuery on my Nova/Mailbox model, but not work. Retunr all mailboxes on database

public static function indexQuery(NovaRequest $request, $query)
{

    $domains = Domain::where('user_id', $request->user()->id)->pluck('domain')->toArray();

    return User::with([
        'domains.mailboxes' => function ($builder) use ($domains) {
            $builder->where('domain',$domains);
        }
    ])->find($user);

    if ($request->user()->is_super_admin) {
        return $query;
    } else {
        return User::with([
            'domains.mailboxes' => function ($builder) use ($domains) {
                $builder->where('domain',$domains);
            }
        ])->find($user);
    }
}

On tinker (thanks to @tykus on post https://laracasts.com/discuss/channels/eloquent/understanding-eager-loading-with-lineal-relationship) workfine, but on Nova, user see all mailbox.

Also if activate MailboxesPolicy in AuthServiceProvider, user only index all mailboxes, but can not edit or delete.

Please sign in or create an account to participate in this conversation.