0
0
Laravelframework~30 mins

Accessors and mutators in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Accessors and Mutators in Laravel Eloquent Models
📖 Scenario: You are building a Laravel application to manage user profiles. You want to automatically format user names when retrieving and saving them in the database.
🎯 Goal: Create a Laravel Eloquent model with an accessor to always return the user's full name in uppercase, and a mutator to store the user's first name capitalized.
📋 What You'll Learn
Create a User model with first_name and last_name attributes
Add an accessor to get the full name in uppercase
Add a mutator to capitalize the first letter of the first name before saving
💡 Why This Matters
🌍 Real World
Accessors and mutators are used in Laravel applications to automatically format or transform data when reading from or writing to the database, such as formatting names, dates, or JSON fields.
💼 Career
Understanding accessors and mutators is essential for Laravel developers to write clean, maintainable code that handles data consistently and reduces errors.
Progress0 / 4 steps
1
Create the User model with first_name and last_name attributes
Create a Laravel Eloquent model class called User with protected properties first_name and last_name in the $fillable array.
Laravel
Need a hint?

Remember to add protected $fillable with the exact attribute names.

2
Add an accessor for the full name in uppercase
Add a public method called getFullNameAttribute in the User model that returns the concatenation of first_name and last_name in uppercase letters.
Laravel
Need a hint?

Accessor methods start with get, end with Attribute, and return the formatted value.

3
Add a mutator to capitalize the first letter of first_name
Add a public method called setFirstNameAttribute in the User model that sets the first_name attribute with the first letter capitalized.
Laravel
Need a hint?

Mutator methods start with set, end with Attribute, and modify the attribute before saving.

4
Complete the User model with both accessor and mutator
Ensure the User model includes the $fillable array, the getFullNameAttribute accessor, and the setFirstNameAttribute mutator methods exactly as specified.
Laravel
Need a hint?

Review all parts to ensure the model works as expected with accessor and mutator.