/ app / Rules / UniqueAliasForUserType.php
UniqueAliasForUserType.php
 1  <?php
 2  
 3  namespace App\Rules;
 4  
 5  use App\Enums\UserTypeEnum;
 6  use App\Models\User;
 7  use Illuminate\Contracts\Validation\Rule;
 8  
 9  class UniqueAliasForUserType implements Rule
10  {
11      /**
12       * Create a new rule instance.
13       *
14       * @return void
15       */
16      public function __construct(protected $userId = null, protected $userTypeId = null)
17      {
18          //
19      }
20  
21      /**
22       * Determine if the validation rule passes.
23       *
24       * @param  string  $attribute
25       * @param  mixed  $value
26       * @return bool
27       */
28      public function passes($attribute, $value)
29      {
30          if ($this->userTypeId != UserTypeEnum::INTERNAL->value) {
31              return true; // Skip validation if user_type_id is not 1
32          }
33  
34          if (empty($value)) {
35              return false; // Alias must not be empty if user_type_id is 1
36          }
37  
38          $query = User::whereAlias($value)->whereUserTypeId(UserTypeEnum::INTERNAL->value);
39  
40          if ($this->userId) {
41              $query->where('id', '!=', $this->userId);
42          }
43  
44          return !$query->exists();
45      }
46  
47      /**
48       * Get the validation error message.
49       *
50       * @return string
51       */
52      public function message()
53      {
54          return 'The alias has already been taken or is invalid for the given user type.';
55      }
56  }