I
I
Ilya2019-07-15 17:12:22
Laravel
Ilya, 2019-07-15 17:12:22

How to get data in model attributes from related Laravel table and output that json without error?

Hey!
Faced an interesting problem in Laravel.
There are two models Item and ItemImages.
I need to get json with all items, everything works until the 'photo' attribute appears (first photo)

class Item extends Model
{
    protected $appends = [
        'photo',
    ];

    public function imgs()
    {
        return $this->hasMany(ItemImage::class);
    }

    public function getPhotoAttribute()
    {
        $img = $this->imgs->first();
        return $img->src;
    }
}

Eventually.
dd(Item::all()); //works
response()->json(['items'=>Item::all()]) //error
Everything works in the views, but trying to get json gives "PHP Fatal error: Allowed memory size of 134217728 bytes" in tinker or 504 error in browser. I remove the 'photo' attribute - it works.
help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2019-07-16
@hrhr99

Solution in Lara's constraints.
If you want json, you cannot access related tables of the current model in model attributes. Gives a memory overflow error.
The documentation does not mention this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question