Farshad
Farshad

Reputation: 2000

How to customize the implode function structure in resource in laravel

In my resource I've got an object like below:

return [
    'something' => $this->somerelationship->implode('name',',')
];

Now it returns this result for me:

{
    something [
        "items,items,items"
    ]
}

But I want my implode to return a useable array in javascript not just making it 1 index of the array rather than that put each item in 1 slot of array-like below:

{
    something 
    [
        {items},{items},{items}"
    ]
}

How can I achieve that now ?

Upvotes: 0

Views: 237

Answers (2)

M. Eriksson
M. Eriksson

Reputation: 13635

Instead of ->implode() (which takes an array and turn it into a string), try and do:

'something' => $this->somerelantionship->pluck('name')->all(),

The method pluck() returns an array with all the values from a specific key, which seems to be what you want.

Upvotes: 1

meph
meph

Reputation: 209

You can return

json_encode($this->somerelationship->pluck('name')->toArray());

Then in your javascripts just JSON.parse() it or put it in a variable in blade:

 var items = {!! json_decode($variable) !!}

Upvotes: 0

Related Questions