Mostafa Kalantari Fard
Mostafa Kalantari Fard

Reputation: 304

How to merge two eloquent model result attributes as new result in Laravel

I have a Laravel product model that has a relation called details. I want to merge the attributes of these two eloquent results together.

My $product attributes are like this:

#attributes: array:7 [▼
    "id" => 1
    "title" => "test"
    "slug" => "test"
    "html" => null
    "published_at" => "2022-01-27 11:01:00"
    "created_at" => "2022-01-27 11:04:15"
    "updated_at" => "2022-01-27 11:05:30"
  ]

Also $product->details attributes are like this:

#attributes: array:6 [▼
    "id" => 1
    "model" => "test"
    "sku" => "test"
    "base_price" => null
    "created_at" => "2022-01-27 11:04:15"
    "updated_at" => "2022-01-27 11:05:30"
  ]

What I need is this result:

#attributes: array:10 [▼
    "id" => 1
    "title" => "test"
    "slug" => "test"
    "html" => null
    "model" => "test"
    "sku" => "test"
    "base_price" => null
    "published_at" => "2022-01-27 11:01:00"
    "created_at" => "2022-01-27 11:04:15"
    "updated_at" => "2022-01-27 11:05:30"
  ]

Notice that these are the eloquent results and are not a simple array.

Upvotes: 1

Views: 1177

Answers (1)

P. K. Tharindu
P. K. Tharindu

Reputation: 2730

You could do the formatting using a API Resource class or simply by using a map() function depending on your project/preference. The API Resource may look something like this:

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'html' => $this->html,
            "model" => $this->details?->model,
            "sku" => $this->details?->sku,
            "base_price" => $this->details?->base_price,
            ...
        ];
    }
}

Upvotes: 2

Related Questions