PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

[FIXED] How to pass first element of nested array using resource collection Laravel

 November 15, 2022     laravel, laravel-6, php     No comments   

Issue

М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.


Solution

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


Answered By - Vimona
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing