-1

I have two files userPolicy.php and userObserver.php , i write some logic inside both files what it does means if a user have any active subscriptions that user won't be deleted upto this it's working fine .

userPolicy.php

  public function delete(User $user, $item)
    {
       $canceled_subscription=new userObserver();
       return (!$canceled_subscription->deleting($item)) && ($user->hasAdminRole());    
    }

userObserver.php

 public function deleting(Plan $item){
//based on $has_subscriptions it should allow to delete or call the userPolicy.php delete function
        $has_subscriptions=$item->subscriptions()->where('status','!=','canceled')->exists();
        return $has_subscriptions;
    }

Now what i want is i want to refactor the code from the the userPolicy.php that means is there any way to reduce the code from the userPolicy.php file (mainly $canceled_subscriptions),is there any chance to reduce the code from userPolicy.php please help me to refactor the code

Code cracker
  • 316
  • 1
  • 5
  • 20

1 Answers1

-1

I prefer to keep the code clean by separating conditions, it's easier to understand it fast. You can use a static function in your User Observer like in the following example.

// UserPolicy
public function delete(User $user, $item) 
{
    if (! $user->hasAdminRole()) return false;

    return UserObserver::deleting();
}

// UserObserver
public static function deleting(Plan $item)
{
    return $item->subscriptions()->where('status','!=','canceled')->exists();
}
maki000
  • 339
  • 1
  • 8
  • it's not working, How observer is communicating with the policy – Code cracker Oct 18 '21 at 11:17
  • This is just a code example, I cannot go any deeper without you providing the whole code for both classes. Did you try to debug it, and what's not working exactly? – maki000 Oct 18 '21 at 11:21