Files
GSB-Construction/app/Observers/UserObserver.php

53 lines
1.7 KiB
PHP

<?php
namespace App\Observers;
use App\Models\User;
use Illuminate\Validation\ValidationException;
class UserObserver
{
/**
* Handle the User "creating" event.
*/
public function creating(User $user): void
{
if ($user->contractor_id) {
$contractor = $user->contractor;
if ($contractor) {
$currentUsersCount = $contractor->users()->count();
// If user_limit is 0, it might mean unlimited, but let's assume it's a hard limit.
// Or if it's > 0, we enforce it.
if ($contractor->user_limit > 0 && $currentUsersCount >= $contractor->user_limit) {
throw ValidationException::withMessages([
'contractor_id' => 'The contractor has reached its maximum user limit of ' . $contractor->user_limit . '.',
]);
}
}
}
}
/**
* Handle the User "updating" event.
*/
public function updating(User $user): void
{
// If the user's contractor_id is changing, check limits on the new contractor
if ($user->isDirty('contractor_id') && $user->contractor_id) {
$contractor = $user->contractor;
if ($contractor) {
$currentUsersCount = $contractor->users()->count();
if ($contractor->user_limit > 0 && $currentUsersCount >= $contractor->user_limit) {
throw ValidationException::withMessages([
'contractor_id' => 'The contractor has reached its maximum user limit of ' . $contractor->user_limit . '.',
]);
}
}
}
}
}