Ilya Vo
Ilya Vo

Reputation: 2309

I can't get the data in appends with json in Laravel

I have two models in laravel project Item and ItemImgs

Item.php

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;
    }

} 

it's worked in views

dd(Item::all()); //worked
{{ $cane->photo}}; //worked

but when I try to get json

    return response()->json([
        'items' => Item::with('imgs')->get(),
    ]);

// not worked. Got timeout 500

Upvotes: 0

Views: 339

Answers (3)

Ilya Vo
Ilya Vo

Reputation: 2309

It is not possible to refer to the linked model tables in attributes. It works in views but gives out a memory error when outputting an array through json.

public function getPhotoAttribute(){ 
   $img = ItemImage::where('item', $this->id)- 
   >first();
} 

It works that way, but it's not elegant.

Upvotes: 0

Rabie Shishko
Rabie Shishko

Reputation: 56

if what you're trying to do is to get the items that have imgs() then what you should do is query by relationship existence, as mentioned in the docs

https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence

'items' => Item::has('imgs')->get()

Upvotes: 0

Roberto Ferro
Roberto Ferro

Reputation: 427

You cannot use dot notation in PHP.

public function getPhotoAttribute()
{
    $img = $this->imgs->first();
    return $img.src; // Dot notation is not allowed
}

but you've to use:

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

Upvotes: 4

Related Questions