📜  laravel set appends - PHP (1)

📅  最后修改于: 2023-12-03 14:43:45.918000             🧑  作者: Mango

Laravel Set Appends - PHP

Laravel provides a way for you to add custom attributes to your model instances that do not have a corresponding column in the database. This is achieved using the $appends property on the model.

Setting Appends

To add a custom attribute to your model, you need to define a getter method for the attribute and add the attribute name to the $appends property on the model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $appends = ['full_name'];

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

In this example, we've added a full_name attribute to the User model. The getFullNameAttribute method returns the full name of the user by concatenating the first_name and last_name properties. We've also added full_name to the $appends property, which tells Laravel to include this attribute when the model is serialized to JSON or returned as an array.

Accessing Appended Attributes

Once you have set up an appended attribute on your model, you can access it just like any other property.

$user = User::find(1);

echo $user->full_name;

In this example, we've loaded a User model using the find method and accessed the full_name attribute by simply calling $user->full_name.

Conclusion

Adding custom attributes to your Laravel model instances using $appends is a powerful tool that can save you time and improve the readability of your code. Whether you're using it to add calculated fields, or simply to provide more descriptive names for commonly-used attributes, $appends is a feature that every Laravel developer should be familiar with.