国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
What Are Accessors?
What About Mutators?
When Should You Use Them?
Final Thoughts
Home PHP Framework Laravel What are accessors and mutators in Eloquent?

What are accessors and mutators in Eloquent?

Jun 17, 2025 am 10:13 AM
eloquent

In Eloquent, accessors and modifiers are used to format or process data when obtaining or setting properties. The accessor is used to modify the attribute values ??retrieved from the database, such as combining fields or formatting dates, and the method is named get{AttributeName}Attribute, such as getFullNameAttribute; the modifier is used to modify the attribute values ??before saving to the database, such as cleaning up the phone number format, and the method is named set{AttributeName}Attribute, such as setPhoneNumberAttribute. Both help maintain data consistency and business logic centralization, and are suitable for data formatting, input standardization, and derived value processing, but should avoid operations that consume time or lead to information loss.

In Eloquent, visitors and mutators are custom methods you can define on your models to format or manipulate data when getting or setting attributes. They're super useful for keeping your data clean and consistent without scattering logic all over your app.

What Are Accessors?

Accessors let you modify the value of an attribute when you retrieve it from the database. You might use them to format dates, combine fields, or apply transformations.

For example, if you have a first_name and last_name field in your database, but often want the full name, you could create an accessor like this:

 public function getFullNameAttribute()
{
    return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
}

Now whenever you call $user->full_name , Eloquent will compute and return that value based on the two fields.

  • Just make sure the method follows the get{AttributeName}Attribute naming convention.
  • The attribute becomes available as if it were a real column in your table.
  • It doesn't save to the database — it's only computed on the fly.

This is handy for things like formatting phone numbers, URLs, or any derived values.

What About Mutators?

Mutators do the opposite — they let you change the value of an attribute before it gets saved to the database.

Let's say users input their phone number with dashes or spaces, but you want to store it consistently without any formatting. A mutator would help here:

 public function setPhoneNumberAttribute($value)
{
    $this->attributes['phone_number'] = preg_replace('/[^0-9]/', '', $value);
}

Now, every time someone assigns a phone number using something like $user->phone_number = '(555) 123-4567' , it'll be stripped down to just 5551234567 before saving.

  • Naming follows the set{AttributeName}Attribute pattern.
  • You're modifying the raw value before it hits the database.
  • Great for normalization or validation before storage.

Just be careful not to mutate something in a way that loses important information unintentionally.

When Should You Use Them?

Use accessors and mutators when:

  • You want to format data consistently across your app.
  • You need to normalize input before storing it.
  • You're combining or deriving values ??that don't need to be stored directly.

They help keep your business logic inside your models, which makes your code easier to maintain and test. But remember, these are PHP methods — so avoid doing anything too heavy in them, especially in accessories that might be called frequently.

Also, if you're building APIs or JSON responses, consider using Laravel's resource classes or appending virtual attributes if needed.

Final Thoughts

Accessors and mutators are simple tools that go a long way toward cleaner code. Once you understand how to use them, you'll find plenty of places where they make your models smarter and your controllers lighter.

You don't need to overuse them, but knowing when and how to apply them helps a lot.

The above is the detailed content of What are accessors and mutators in Eloquent?. 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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Implementation of optimistic locking in Laravel Eloquent model Implementation of optimistic locking in Laravel Eloquent model Apr 21, 2023 pm 03:53 PM

This article brings you relevant knowledge about Laravel. It mainly introduces to you the implementation of optimistic locking in the Laravel Eloquent model. There are code examples. Friends who are interested can take a look below. I hope it will be helpful to you.

Laravel development: How to implement polymorphic associations using Laravel Eloquent? Laravel development: How to implement polymorphic associations using Laravel Eloquent? Jun 13, 2023 pm 04:41 PM

Laravel development: How to use LaravelEloquent to implement polymorphic associations? Polymorphic association is an important feature of Laravel Eloquent, which allows one model to establish relationships with multiple different models. In practical applications, processing different types of data is relatively simple and efficient, especially in database design. In this article, we will discuss how to implement polymorphic associations using Laravel Eloquent. 1. What is a polymorphic association? Polymorphism

How to use Eloquent to convert array to object in Laravel? How to use Eloquent to convert array to object in Laravel? Apr 29, 2024 pm 05:42 PM

Converting an array into an object using Eloquent in Laravel requires the following steps: Create an Eloquent model. Use Eloquent's select method to get the result and convert it to an array. Use ArrayObject to convert an array into an object. Gets an object property to access an array's values.

Laravel development: How to implement model association using Laravel Eloquent? Laravel development: How to implement model association using Laravel Eloquent? Jun 13, 2023 am 10:47 AM

Laravel is a popular PHP framework that includes the powerful ORM (Object Relational Mapping) library-LaravelEloquent. This library is very powerful and can help us easily implement model association, making it easier to manage and query data. But many developers don't know how to use Laravel Eloquent to implement model association. In this article, I will introduce how to implement model association using Laravel Eloquent. 1. Laravel

Laravel development: How to build a model using Laravel Eloquent? Laravel development: How to build a model using Laravel Eloquent? Jun 14, 2023 am 10:14 AM

Laravel is a popular PHP web framework that is popular due to its simplicity and ease of use. The Laravel framework is known for its excellent implementation of EloquentORM, an Object-RelationalMini mapping that supports the use of PHP to define database models and provides easy database interaction based on these models. This article will detail how to build a model using Laravel Eloquent to interact with the database quickly and reliably.

Laravel development: How to build a database model using Laravel Eloquent? Laravel development: How to build a database model using Laravel Eloquent? Jun 14, 2023 am 08:21 AM

Laravel development: How to build a database model using LaravelEloquent? Laravel is a popular PHP framework that provides a powerful and easy-to-use database operation tool - Laravel Eloquent. In the past, using PHP to perform database operations inevitably required writing a large number of lengthy SQL statements and cumbersome codes. However, using Laravel Eloquent can easily build database models and achieve rapid development and maintenance. This article

ORM extension library in PHP8.0: Eloquent ORM extension library in PHP8.0: Eloquent May 14, 2023 am 10:22 AM

As developers' needs for data interaction continue to grow, ORM has become an indispensable part of modern development. It can hide database operations in the background and provide a simplified API for CRUD operations. Among these ORM libraries, Eloquent has attracted the attention of many developers because it has been widely used in the Laravel framework. In PHP 8.0, Eloquent comes as a standalone extension library and can now be used in your projects. In this article we will explore Eloq

Using Laravel's Eloquent ORM in ThinkPHP6 Using Laravel's Eloquent ORM in ThinkPHP6 Jun 20, 2023 am 09:40 AM

ThinkPHP6 is a very popular PHP framework, and Laravel is another popular PHP framework. Both frameworks have their own features and advantages, but Laravel's EloquentORM (Object Relational Mapping) engine is known as "the best ORM in the PHP world". What should we do if we want to use Laravel's EloquentORM when using ThinkPHP6? Let us discuss ThinkPHP in detail below

See all articles