Team Sales
Team Sales

Reputation: 1

Laravel eloquent get related model as column_name => value

I have a Product table related with Image table, one to many relationship.

How do I get Image records not as array? Instead, return only 1 Image record as column_name: value

This code:

$products = $request->user()->products()->orderBy('id', 'desc')->with(['images' => function($query) {
            $query->where('featured', 1)->limit(1);
        }])->get();

Is returning data like this :

{
        "id": 13,
        "name": "Shoes",
        "price": "3.00",
        "stock": 5,
        "pivot": {
            "user_id": 7,
            "product_id": 13
        },
        "images": [
            {
                "id": 5,
                "file": "5da9d9b493403.png",
                "featured" 1,
                "pivot": {
                    "product_id": 13,
                    "image_id": 5
                }
            }
        ]
    }
}

How to make it return like this?

{
        "id": 13,
        "name": "Shoes",
        "price": "3.00",
        "stock": 5,
        "pivot": {
            "user_id": 7,
            "product_id": 13
        },
        "images": "5da9d9b493403.png"
    }
}

Upvotes: 0

Views: 580

Answers (2)

Jinga Laurentiu
Jinga Laurentiu

Reputation: 35

In the Product model

protected $appends = ['images'];

public function images()
{
    return $this->hasMany('App\Image')->select(['name'])->first();
}

select the name only and return first relation

Upvotes: 0

Salim Djerbouh
Salim Djerbouh

Reputation: 11044

You can append a custom accessor that gets the first image from the relationship

In the Product model

protected $appends = ['images'];

public function getImagesAttribute()
{
    return $this->images()->where('featured', 1)->first()->file;
}

public function images()
{
    return $this->hasMany('App\Image');
}

Then just return the query without eager loading

$products = $request->user()->products()->orderBy('id', 'desc')->get();

Hope this helps

Upvotes: 1

Related Questions