Phone number cast

This commit is contained in:
Matt Young 2026-01-28 01:19:47 -06:00
parent 6bcd8dcb5f
commit 4fd2d11137
5 changed files with 48 additions and 4 deletions

View File

@ -0,0 +1,33 @@
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
class PhoneNumberCast implements CastsAttributes
{
public function get(Model $model, string $key, $value, array $attributes): ?string
{
if ($value === null) {
return null;
}
return match (strlen($value)) {
7 => substr($value, 0, 3).'-'.substr($value, 3),
10 => '('.substr($value, 0, 3).') '.substr($value, 3, 3).'-'.substr($value, 6),
default => strlen($value) > 10
? '+'.substr($value, 0, -10).' ('.substr($value, -10, 3).') '.substr($value, -7, 3).'-'.substr($value,
-4)
: $value,
};
}
public function set(Model $model, string $key, $value, array $attributes)
{
if ($value === null) {
return null;
}
return preg_replace('/\D/', '', $value);
}
}

View File

@ -2,6 +2,7 @@
namespace App\Models;
use App\Casts\PhoneNumberCast;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@ -13,6 +14,10 @@ class Contact extends Model
public $fillable = ['first_name', 'last_name', 'email', 'phone'];
public $casts = [
'phone' => PhoneNumberCast::class,
];
public function clients(): BelongsToMany
{
return $this->belongsToMany(Client::class);

View File

@ -27,7 +27,10 @@ class ClientFactory extends Factory
public function withContact(?Contact $contact = null): static
{
return $this->afterCreating(function (Client $client) use ($contact) {
$client->contacts()->attach($contact ?? Contact::factory()->create());
$client->contacts()->attach(
$contact ?? Contact::factory()->create(),
['is_primary' => true]
);
});
}
}

View File

@ -23,7 +23,10 @@ class ContactFactory extends Factory
public function withClient(?Client $client = null): static
{
return $this->afterCreating(function (Contact $contact) use ($client) {
$contact->clients()->attach($client ?? Client::factory()->create());
$contact->clients()->attach(
$client ?? Client::factory()->create(),
['is_primary' => true]
);
});
}
}

View File

@ -15,8 +15,8 @@ return new class extends Migration
{
Schema::create('client_contact', function (Blueprint $table) {
$table->id();
$table->foreignIdFor(Client::class)->constrained();
$table->foreignIdFor(Contact::class)->constrained();
$table->foreignIdFor(Client::class)->constrained()->cascadeOnDelete();
$table->foreignIdFor(Contact::class)->constrained()->cascadeOnDelete();
$table->boolean('is_primary')->default(false);
$table->timestamps();