Forum

Laravel list DB values into an Array Object

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

murilolivorato
murilolivorato
  • 3 months ago