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

108 lines
2.6 KiB
PHP
Raw Permalink Normal View History

2023-03-28 14:37:49 +00:00
<?php
namespace App\Models;
2026-02-12 16:09:21 +01:00
use App\Enums\Users\RoleEnum;
use App\Traits\Models\ActivityLog;
2026-02-12 16:09:21 +01:00
use Illuminate\Auth\Access\AuthorizationException;
2023-03-28 14:37:49 +00:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
2026-04-08 09:42:05 +02:00
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
2023-03-28 14:37:49 +00:00
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory;
use Notifiable;
use ActivityLog;
2023-03-28 14:37:49 +00:00
/**
* The attributes that are mass assignable.
*
2026-02-12 16:09:21 +01:00
* @var list<string>
2023-03-28 14:37:49 +00:00
*/
protected $fillable = [
'firstname',
'lastname',
'email',
2026-02-12 16:09:21 +01:00
'role',
2023-03-28 14:37:49 +00:00
];
/**
* The attributes that should be hidden for serialization.
*
2026-02-12 16:09:21 +01:00
* @var list<string>
2023-03-28 14:37:49 +00:00
*/
protected $hidden = [
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
2026-02-12 16:09:21 +01:00
'role' => RoleEnum::class,
'last_connection' => 'date',
2023-03-28 14:37:49 +00:00
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
2026-02-12 16:09:21 +01:00
static::creating(function (self $model) {
self::checkElevationPrivileges($model);
2023-03-28 14:37:49 +00:00
});
2026-02-12 16:09:21 +01:00
static::updating(function (self $model) {
self::checkElevationPrivileges($model);
2023-03-28 14:37:49 +00:00
});
}
2026-02-12 16:09:21 +01:00
/**
* 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
);
}
2026-04-08 09:42:05 +02:00
/**
* 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);
}
2023-03-28 14:37:49 +00:00
}