Ad

Laravel Scopes With Relation And Conditions

- 1 answer

i have this laravel scope code

public function apply(Builder $builder, Model $model)
{
    $builder->whereDoesntHave('getPermissionData');
}

everything working fine till now what i need is to wright conditions like this

public function apply(Builder $builder, Model $model)
{
    /*
        if($builder->whereHas('getPermissionData'))
        {
            check the relation 
            and do some code here
        }
    */
    $builder->whereDoesntHave('getPermissionData');
}

is that possible or not

Ad

Answer

You need to create two different conditions in or with each others. You also should wrap this condition in a where clause so next conditions won't be in or aswell

public function apply(Builder $builder, Model $model) {
    $builder->where(function ($query) {
         $query->whereDoesntHave('getPermissionData')
               ->orWhereHas('getPermissionData', function ($permissionQuery) {
                   // Apply your condition to the relation query
               });
    });
}
Ad
source: stackoverflow.com
Ad