Home > Mobile >  How to pass first element of nested array using resource collection Laravel
How to pass first element of nested array using resource collection Laravel

Time:07-16

Мy Controller

    public function index()
    {
          return AdvertResource::collection(Advert::with('image')
              ->paginate(10));
    }

Method image in Advert Model

    public function image()
    {
        return $this->hasMany(AdvertImage::class);
    }

Мy AdvertResource

    public function toArray($request)
    {
        return [
            'title' => $this->title,
            'price' => $this->price,
            'image' => AdvertImgResource::collection($this->image),
            'created_at' => $this->created_at
        ];
    }

Мy AdvertImgResource

    public function toArray($request)
    {
        return [
            'path' => $this->path,
        ];
    }

The data I receive

        {
            "title": "title",
            "price": 500,
            "image": [
                {
                    "path": "img1"
                    "path": "img2"
                    "path": "img3"
                }
            ],
            "created_at": "2022-07-14T18:14:37.000000Z"
        },

Each ad has several photos, I need to display the main photo (the first one in the list) Can you tell me if it is possible to display the first element of the path array for each object? It should also be inside the index method, because in the show method I will get all the elements in full.

CodePudding user response:

I think it can be done by adding a new value to the return array in AdvertImgResource like following:

//AdvertResource
public function toArray($request)
{
    $images = AdvertImgResource::collection($this->image); //Retrieve image collection here to access the first image in the array.

    return [
        'title' => $this->title,
        'price' => $this->price,
        'image' => $images,
        'first_image' => $images->first(), //Retrieves the first image or returns null if the images collection is empty.
        'created_at' => $this->created_at
    ];
}
  • Related