pingcrm/app/Models/User.php

104 lines
2.7 KiB
PHP
Raw Normal View History

2019-03-05 18:10:11 -03:00
<?php
2020-09-08 19:45:49 -03:00
namespace App\Models;
2019-03-05 18:10:11 -03:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
2019-03-18 08:53:00 -03:00
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
2020-07-29 11:58:25 -03:00
use Illuminate\Support\Facades\Hash;
2021-12-08 13:59:08 -03:00
use Laravel\Sanctum\HasApiTokens;
2019-03-05 18:10:11 -03:00
class User extends Authenticatable
2019-03-05 18:10:11 -03:00
{
2021-12-08 13:59:08 -03:00
use HasApiTokens, HasFactory, Notifiable, SoftDeletes;
2019-03-18 08:53:00 -03:00
2021-12-08 13:59:08 -03: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>
*/
2019-04-03 06:24:11 -03:00
protected $casts = [
'owner' => 'boolean',
'email_verified_at' => 'datetime',
2019-04-03 06:24:11 -03:00
];
public function resolveRouteBinding($value, $field = null)
{
return $this->where($field ?? 'id', $value)->withTrashed()->firstOrFail();
}
2019-03-18 08:53:00 -03:00
public function account()
{
return $this->belongsTo(Account::class);
}
public function getNameAttribute()
{
return $this->first_name.' '.$this->last_name;
}
public function setPasswordAttribute($password)
{
$this->attributes['password'] = Hash::needsRehash($password) ? Hash::make($password) : $password;
2019-03-18 08:53:00 -03:00
}
public function isDemoUser()
{
2019-12-19 10:50:26 -03:00
return $this->email === 'johndoe@example.com';
}
2019-03-18 08:53:00 -03:00
public function scopeOrderByName($query)
{
$query->orderBy('last_name')->orderBy('first_name');
}
public function scopeWhereRole($query, $role)
{
switch ($role) {
case 'user': return $query->where('owner', false);
case 'owner': return $query->where('owner', true);
}
}
public function scopeFilter($query, array $filters)
{
$query->when($filters['search'] ?? null, function ($query, $search) {
$query->where(function ($query) use ($search) {
$query->where('first_name', 'like', '%'.$search.'%')
->orWhere('last_name', 'like', '%'.$search.'%')
->orWhere('email', 'like', '%'.$search.'%');
2019-03-18 08:53:00 -03:00
});
})->when($filters['role'] ?? null, function ($query, $role) {
$query->whereRole($role);
})->when($filters['trashed'] ?? null, function ($query, $trashed) {
if ($trashed === 'with') {
$query->withTrashed();
} elseif ($trashed === 'only') {
$query->onlyTrashed();
}
});
}
2019-03-05 18:10:11 -03:00
}