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

Amit Merchant · March 26, 2019 ·

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 (and 8.1), 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-read 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.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!