ldc-loue/app/Models/User.php

89 lines
2.2 KiB
PHP
Raw Normal View History

2022-05-20 11:54:44 +02:00
<?php
namespace App\Models;
2022-06-01 13:41:24 +02:00
use App\Lib\ToolboxHelper;
2022-05-20 11:54:44 +02:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
2022-06-01 13:41:24 +02:00
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
2022-05-20 11:54:44 +02:00
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
2022-06-01 13:41:24 +02:00
use HasApiTokens;
use HasFactory;
use Notifiable;
2022-05-20 11:54:44 +02:00
/**
* 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',
2022-06-01 13:41:24 +02:00
'last_connection' => 'datetime',
2022-05-20 11:54:44 +02:00
];
2022-06-01 13:41:24 +02:00
/**
* 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);
2022-06-01 13:41:24 +02:00
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);
2022-06-01 13:41:24 +02:00
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
2022-06-01 13:41:24 +02:00
* @return void
* @throws \Illuminate\Validation\ValidationException If user email as already used.
*/
private static function assertEmailIsUnique($email, ?int $id = null)
2022-06-01 13:41:24 +02:00
{
ToolboxHelper::assertFieldIsUnique((new self())->getTable(), 'email', $email, $id);
2022-06-01 13:41:24 +02:00
}
2022-05-20 11:54:44 +02:00
}