QA
Beginner LevelLaravel

How do Eloquent Accessors, Mutators, and Attribute Casting work?

❓ Interview Prompt: Explain Attribute::make() accessor/mutator syntax, $casts property (json, boolean, datetime, encrypted), and model attributes.

Accessors format attribute values when retrieved, Mutators format values before database saving, and '$casts' handles automatic type conversion:

Modern Attribute Syntax (Laravel 9+):

Use 'Attribute::make(get: fn ($val) => ..., set: fn ($val) => ...)' inside model methods.

Attribute Casting:

'$casts = ["settings" => "array", "is_active" => "boolean"]' converts JSON strings to PHP arrays automatically!

Code Implementation Example

php
<?php
namespace AppModels;

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentCastsAttribute;

class User extends Model
{
    protected $casts = [
        'is_admin' => 'boolean',
        'options' => 'array',
    ];

    protected function name(): Attribute {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value),
            set: fn (string $value) => strtolower($value)
        );
    }
}
💡Defining Eloquent Accessors, Mutators, and Attribute Casting.
🎯 Interview Key Takeaway

Use Attribute::make() for custom value formatting and $casts for automatic JSON/Boolean database type conversion.

#Accessors#Mutators#Casting#Eloquent#Beginner
Back to all Laravel Questions→

More Laravel Interview Questions

Beginner LevelLaravel

How does the Laravel Service Container manage Dependency Injection and Bindings?

Beginner LevelLaravel

How does Routing work in Laravel including Named Routes and Route Parameters?

Beginner LevelLaravel

What is Blade Templating and how do custom directives work?