Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mnrafg's avatar

Eager loading custom attribute (accessor)

I have the following model:

<?php

// Category.php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['category_name', 'description'];
    
    // Custom accessor can be accessed by $category->short_description
    public function getShortDescriptionAttribute() {
        return str_limit($this->description, 30);
    }
}

Now I want to get list of the categories with eager loaded short_descriptionattribute.

<?php

$allCategories = App\Category::all();

// this does not work
// $categories = App\Category::with('short_description')->get();

// but this will not contain short_description
dump($allCategories->toJson());

Any help will be appreciated.

0 likes
3 replies
Cronix's avatar
Cronix
Best Answer
Level 67

An accessor is only used when directly calling the accessor method ($model->accessor) and retrieving something from the model. So when you cast it to json, it's missing because it was never called.

A workaround is to add the attribute to the $appends array in your Category model

protected $appends = ['short_description'];

https://laravel.com/docs/5.6/eloquent-serialization#appending-values-to-json

16 likes
mnrafg's avatar

Thanks, your reply solved my problem.

Please or to participate in this conversation.