user1996959
user1996959

Reputation: 119

Laravel 5.5, how to disable autoappending relations to Array/JSON?

Here's two classes:

class Category extends Model {

    protected $fillable = [
        'title', 'slug'
    ];

    protected $appends = [
        'url'
    ];

    public function subcategories()
    {
        return $this->hasMany(Subcategory::class);
    }

    public function getUrlAttribute()
    {
        return route('catalog::category', ['catSlug' => $this->slug]);
    }
}

class Subcategory extends Model {

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'slug'
    ];

    protected $appends = [
        'url'
    ];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function getUrlAttribute()
    {
        return route('catalog::subcategory', ['catSlug' => $this->category->slug, 'subcatSlug' => $this->slug]);
    }
}

Next, lets use toArray() method on Category :

$category = Category::first();
dd($category->toArray()); 

Array looks like expected: id, title, slug, and appended url field. But if I'm use any call to relations, they autoappended to array:

$category = Category::first();
$category->subcategories;
dd($category->toArray());

And now array contains also field "subcategories", each item there contains "category", and starts endless recursion. This won't happens if use calls like $category->subcategories()->get() , but this is not good solution for me

Upvotes: 1

Views: 1623

Answers (1)

Anderson Andrade
Anderson Andrade

Reputation: 579

You can use the $hidden attribute to define which fields should be hidden when your model have been Serialized. See more on

https://laravel.com/docs/5.5/eloquent-serialization#hiding-attributes-from-json

Upvotes: 2

Related Questions