How to Retrieve Custom Attributes in Laravel Models on Object Load?

Susan Sarandon
Release: 2024-10-29 12:43:29
Original
723 people have browsed it

How to Retrieve Custom Attributes in Laravel Models on Object Load?

Retrieve Custom Attributes in Laravel Models on Object Load

Problem:

You wish to access custom attributes/properties on a Laravel/Eloquent model upon model loading, without relying on manual loops.

Solution:

Laravel 8 :

Define your custom attribute as an Attribute with a getter function:

<code class="php">class EventSession extends Eloquent {
    public function availability() {
        return new Attribute(
            get: fn() => $this->calculateAvailability()
        );
    }
}</code>
Copy after login

Laravel 8-:

Method 1: Append your custom attribute to the $appends array and create a corresponding accessor:

<code class="php">class EventSession extends Eloquent {
    protected $appends = ['availability'];

    public function getAvailabilityAttribute() {
        return $this->calculateAvailability();
    }
}</code>
Copy after login

Method 2: Override the toArray() method to explicitly include your attribute:

<code class="php">class Book extends Eloquent {
    public function toArray() {
        $array = parent::toArray();
        $array['upper'] = $this->upper;
        return $array;
    }

    public function getUpperAttribute() {
        return strtoupper($this->title);
    }
}</code>
Copy after login

Method 3: Iterate through mutated attributes in toArray():

<code class="php">class Book extends Eloquent {
    public function toArray() {
        $array = parent::toArray();
        foreach ($this->getMutatedAttributes() as $key) {
            if (!array_key_exists($key, $array)) {
                $array[$key] = $this->{$key};
            }
        }
        return $array;
    }

    public function getUpperAttribute() {
        return strtoupper($this->title);
    }
}</code>
Copy after login

The above is the detailed content of How to Retrieve Custom Attributes in Laravel Models on Object Load?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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