Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Fetching dynamic attributes for models on-the-fly in Laravel

There exist this neat feature in Laravel using which you can add attributes in the models that do not have a respective column in your database.

You can achieve this by first creating an accessor for the attribute you want to be returned when casting models to an array or JSON. You can create an accessor like below.

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['is_admin'];

    /**
     * Get the administrator flag for the post.
     *
     * @return bool
     */
    public function getIsEditable()
    {
        return $this->attributes['admin'] == 'yes';
    }
}

Notice here that, you need to add the attribute name to the appends property on the model. Also note that, attribute names are typically referenced in snake case, even though the accessor is defined using camel case.

Once the attribute has been added to the appends list, it will be included in both the model’s array and JSON representations.

You may also like: Packages to make your Laravel development experience awesome.

Fetching dynamic attributes on run time

You can use the append method on model instance to append attributes on-the-fly.

return $post->append('is_editable')->toArray();

Or if you can use setAppends method, if you want to append multiple attributes like so.

return $post->setAppends(['is_editable', 'is_expired'])->toJson();
Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?