Backend Development 7 min read

Method‑Based Model Casting in Laravel 11

Laravel 11 introduces a method‑based model casting system that replaces the traditional $casts property, allowing developers to define type conversions via Attribute methods, which improves code clarity, flexibility, testability, and overall maintainability of Eloquent models.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Method‑Based Model Casting in Laravel 11

Laravel is renowned for its elegant syntax and efficient backend web development capabilities, continually leading PHP framework innovation. With the release of Laravel 11 , the framework makes a major breakthrough in model casting, introducing a method‑based approach that fundamentally changes how developers interact with Eloquent models.

What was model casting before Laravel 11?

Prior to Laravel 11 , model casting was achieved by defining a $casts property on an Eloquent model. The $casts property automatically converts model attributes to common data types such as array, JSON, or collection when they are accessed.

Example:

<code>class User extends Model
{
    protected $casts = [
        'settings' => 'array',
    ];
}

$user = User::find(1);

// The 'settings' attribute is cast to an array
$settings = $user->settings;
</code>

Transition to method‑based model casting in Laravel 11

Laravel 11 introduces a paradigm shift, moving type conversion from properties to methods. This change enhances code flexibility and readability. Developers now define conversion logic by returning a Cast instance from a method instead of using a property array.

The basic workflow is illustrated below:

<code>public function rates(): Attribute
{
    return Attribute::make(
        get: fn ($value) => json_decode($value, true),
        set: fn ($value) => json_encode($value),
    );
}
</code>

In this example, the settings method represents a custom cast. It returns an Attribute instance whose get and set closures define how the value is retrieved and stored.

Advantages of method‑based model casting

1. Clarity and context: Separating casting logic from model attributes makes the code clearer and more readable. Each casting method provides explicit context for its purpose, improving maintainability.

2. Customization: Developers can embed complex logic within the get and set closures, offering greater flexibility without altering the underlying attribute definition.

3. Testability: Isolating casting into methods simplifies testing; each method can be unit‑tested independently, ensuring correctness and overall code quality.

How to implement method‑based casting

Implementing method‑based casting is straightforward. Follow these steps:

1. Define the method: Create a method on the Eloquent model whose name matches the attribute you wish to cast.

2. Return an Attribute instance: The method should return an Attribute object provided by Laravel.

3. Define get and set logic: Inside the Attribute instance, supply get and set closures that specify how to retrieve and store the attribute value.

Examples

Common scenarios illustrate the power of method‑based casting:

1. Currency conversion: Automatically convert stored cents to dollars on retrieval and vice‑versa on saving.

<code>public function price(): Attribute
{
    return Attribute::make(
        get: fn ($value) => $value / 100,
        set: fn ($value) => $value * 100,
    );
}
</code>

2. Date formatting: Format date attributes without extra accessor or mutator methods.

<code>public function dob(): Attribute
{
    return Attribute::make(
        get: fn ($value) => $value->format('Y-m-d'),
        set: fn ($value) => Carbon::parse($value),
    );
}
</code>

3. Encryption and decryption: Handle encryption directly within the model for secure data storage.

<code>public function password(): Attribute
{
    return Attribute::make(
        get: fn ($value) => Crypt::decrypt($value),
        set: fn ($value) => Crypt::encrypt($value),
    );
}
</code>

Method‑based model casting provides a flexible, customizable, and testable solution for handling data type conversions in Laravel models.

Conclusion

Method‑based model casting in Laravel 11 is a significant improvement that promotes better coding practices, enhances readability, and offers unparalleled flexibility. This change reflects the Laravel team's commitment to continuous evolution and prioritizes the developer experience.

backend-developmentPHPLaravelEloquentAttributeLaravel 11Model Casting
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.