<?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());
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