ldc-crm/app/Models/CustomerInfo.php
2023-06-30 14:59:07 +02:00

121 lines
2.7 KiB
PHP

<?php
namespace App\Models;
use App\Enums\Country;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Kwaadpepper\Enum\Traits\CastsEnums;
class CustomerInfo extends Model
{
use HasFactory;
use CastsEnums;
/**
* Map attribute names to enum classes.
*
* @var array
*/
protected $enumCasts = [
'country' => Country::class
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'opt_in' => 'bool'
];
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $fillable = [
'firstname',
'lastname',
'birth_date',
'address',
'address2',
'phone',
'country',
'city',
'postcode',
'opt_in'
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::creating(function (self $model) {
$model->hashcode = Str::uuid();
});
static::deleting(function (self $model) {
CustomerOptInHistory::query()->whereHas('customer', function (Builder $q) use ($model) {
$q->where('id', $model->customer->id);
})->whereHas('brand', function (Builder $q) use ($model) {
$q->where('id', $model->brand->id);
})->delete();
});
}
// * RELATIONS
/**
* Customer BelongsTo relation
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function customer()
{
return $this->belongsTo(Customer::class);
}
/**
* get Login
*
* @return \App\Models\CustomerLogin
*/
public function login()
{
return $this->customer->login($this->brand);
}
/**
* Brand BelongsTo relation
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function brand()
{
return $this->belongsTo(Brand::class);
}
// * METHODS
/**
* Get customer info from email
*
* @param \App\Models\Brand $brand
* @param string $email
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function getFromEmail(Brand $brand, string $email)
{
return CustomerInfo::query()->whereHas('brand', function (Builder $q) use ($brand) {
$q->where('id', $brand->id);
})->whereHas('customer', function (Builder $q) use ($email) {
$q->where('email', $email);
});
}
}