Andreas Hunter
Andreas Hunter

Reputation: 5004

Override eloquent relationship result data

I use Laravel-Metable package in my project. This package return collection object using in key meta name and on value eloquent object.

Here you can see package data result screenshot.

How I can override result data and get this type of array data:

$meta = [
    [
        'id' => 1,
        'key' => "Meta Name",
        'value' => "Meta Value"

    ],

    [
        'id' => 2,
        'key' => "Meta Name",
        'value' => "Meta Value"

    ],
];

I will load my models meta with lazy loading:

use Metable;

protected $with = ['meta'];

Upvotes: 0

Views: 458

Answers (1)

nakov
nakov

Reputation: 14268

You can use the collection map method for that so it should be something like this:

$result = $metaItems->map(function($meta) {
    return [
        'id' => $meta->id,
        'key' => $meta->key,
        'value' => $meta->value
    ];
})->values();

// then $result->toArray(); should give you the expected result

Upvotes: 1

Related Questions