86 lines
2.2 KiB
PHP
86 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Lib\ToolboxHelper;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Foundation\Auth\User as Authenticatable;
|
|
use Illuminate\Notifications\Notifiable;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Support\Str;
|
|
|
|
class User extends Authenticatable
|
|
{
|
|
use HasFactory;
|
|
use Notifiable;
|
|
|
|
/**
|
|
* The attributes that are mass assignable.
|
|
*
|
|
* @var array<int, string>
|
|
*/
|
|
protected $fillable = [
|
|
'name',
|
|
'email',
|
|
'password',
|
|
];
|
|
|
|
/**
|
|
* The attributes that should be hidden for serialization.
|
|
*
|
|
* @var array<int, string>
|
|
*/
|
|
protected $hidden = [
|
|
'password',
|
|
'remember_token',
|
|
];
|
|
|
|
/**
|
|
* The attributes that should be cast.
|
|
*
|
|
* @var array<string, string>
|
|
*/
|
|
protected $casts = [
|
|
'email_verified_at' => 'datetime',
|
|
'last_connection' => 'datetime',
|
|
];
|
|
|
|
/**
|
|
* Perform any actions required after the model boots.
|
|
*
|
|
* @return void
|
|
*/
|
|
protected static function booted()
|
|
{
|
|
// * EVENT CLOSURES.
|
|
static::creating(function (self $user) {
|
|
static::assertEmailIsUnique($user->email);
|
|
if (Hash::needsRehash($user->password)) {
|
|
$user->password = Hash::make($user->password);
|
|
}
|
|
$user->remember_token = Str::random(10);
|
|
});
|
|
static::updating(function (self $user) {
|
|
static::assertEmailIsUnique($user->email, $user->id);
|
|
if (Hash::needsRehash($user->password)) {
|
|
$user->password = Hash::make($user->password);
|
|
}
|
|
$user->remember_token = Str::random(10);
|
|
});
|
|
}
|
|
|
|
// * METHODS
|
|
|
|
/**
|
|
* Asserts using validation that the email is unique
|
|
*
|
|
* @param mixed $email
|
|
* @param integer|null $id
|
|
* @return void
|
|
* @throws \Illuminate\Validation\ValidationException If user email as already used.
|
|
*/
|
|
private static function assertEmailIsUnique($email, ?int $id = null)
|
|
{
|
|
ToolboxHelper::assertFieldIsUnique((new self())->getTable(), 'email', $email, $id);
|
|
}
|
|
}
|