Home > Backend Development > PHP Tutorial > Customizing Data Transformations with Laravel Casts

Customizing Data Transformations with Laravel Casts

百草
Release: 2025-03-06 02:31:09
Original
809 people have browsed it

Customizing Data Transformations with Laravel Casts

Laravel's custom casts feature allows customized data conversion, beyond the built-in casting capabilities to handle complex data types and business logic.

The following is an example of how to format phone numbers using custom casts:

<?php namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;

class PhoneNumber implements CastsAttributes
{
    public function get(Model $model, string $key, mixed $value, array $attributes): string
    {
        return sprintf(
            "+%d (%d) %d-%d",
            ...explode('|', $value)
        );
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): string
    {
        $value = preg_replace('/[^0-9]/', '', $value);
        return implode('|', [
            substr($value, 0, 1),
            substr($value, 1, 3),
            substr($value, 4, 3),
            substr($value, 7)
        ]);
    }
}
Copy after login

Another example of address formatting:

<?php namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;

class Address implements CastsAttributes
{
    public function get(Model $model, string $key, mixed $value, array $attributes): array
    {
        $data = json_decode($value, true);

        return [
            'street' => $data['street'],
            'city' => $data['city'],
            'state' => $data['state'],
            'postal_code' => $data['postal_code'],
            'formatted' => sprintf(
                '%s, %s, %s %s',
                $data['street'],
                $data['city'],
                $data['state'],
                $data['postal_code']
            )
        ];
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): string
    {
        return json_encode([
            'street' => $value['street'],
            'city' => $value['city'],
            'state' => $value['state'],
            'postal_code' => $value['postal_code']
        ]);
    }
}
Copy after login

Then, in your model you can use them like this:

class User extends Model
{
    protected $casts = [
        'address' => Address::class,
        'phone' => PhoneNumber::class
    ];
}
Copy after login

Custom casts provide a simple, reusable way to handle complex data transformations while keeping the model simple and easy to maintain.

The above is the detailed content of Customizing Data Transformations with Laravel Casts. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template