Support the ongoing development of Laravel.io →
Laravel.io

Hello Guys , I have a question maybe some one can help me . I want to list my db values object -> id and title , like this -

[ 'id' => 1 , 'title' => my title ]  , [ 'id' => 2 , 'title' => my title 2 ] .......

Becose I want use this in Vue , and I will trnsform this into an Js Object like this - {id: 1 , title: my title }{id: 2 , title: my title 2}

well I got the value from db like this -

 $post= collect(Post::orderBy('created_at', 'desc')->get());

$keyed = $post->mapWithKeys(function ($item) {

            return [$item['id'] => $item['title']];
        });

its bring this result to me -

   [0] => title 1
            [1] => title 2
            [2] => title 3

But I wold like this instead -

 ['id' => 0, 'title' => title 1] ,  ['id' => 1, 'title' => title 2]

So I did like this -

  $post= collect(Post::orderBy('created_at', 'desc')->get());

$keyed = $post->mapWithKeys(function ($item) {

            return ['id' => $item['id'] , 'title' =>  $item['title']];
        });

And it will brings me just ONE result -

    Array
(
    [id] => 74
    [title] => bbbbbb
)

It is look like , its need to different arrays keys , so its dont brings me more items .

does some one knows how could I bring all those values into onject keys ? thanks

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.