ldc-qrcollector-back/app/Models/User.php

107 lines
2.6 KiB
PHP

<?php
namespace App\Models;
use App\Enums\Users\RoleEnum;
use App\Traits\Models\ActivityLog;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory;
use Notifiable;
use ActivityLog;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'firstname',
'lastname',
'email',
'role',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'role' => RoleEnum::class,
'last_connection' => 'date',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::creating(function (self $model) {
self::checkElevationPrivileges($model);
});
static::updating(function (self $model) {
self::checkElevationPrivileges($model);
});
}
/**
* Prevent user elevation privileges.
*
* @param self $user
* @return void
*/
private static function checkElevationPrivileges(self $user): void
{
throw_if(
auth('backend')->user() and auth('backend')->user()->role->value() > $user->role->value(),
AuthorizationException::class
);
}
/**
* Get related brands or all the brands if the user is consceptor.
*
* @return \Illuminate\Database\Eloquent\Collection<int, \App\Models\Brand>|
* \Illuminate\Database\Eloquent\Relations\BelongsToMany<\App\Models\Brand,
* $this,
* \Illuminate\Database\Eloquent\Relations\Pivot>
*/
public function getRelatedBrands()
{
return $this->role->equals(RoleEnum::conceptor) ?
Brand::all() :
$this->brands;
}
// * RELATIONSHIPS
/**
* The brands that belong to the user.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany<\App\Models\Brand,
* $this,
* \Illuminate\Database\Eloquent\Relations\Pivot>
*/
public function brands(): BelongsToMany
{
return $this->belongsToMany(Brand::class);
}
}