Hi @raygun,
There are a couple of different ways how you can do this. I will first show some examples where we're only using normal PHP behavior.
First you could create an $resulst array and then pass all of the posts into that,
$results = [];
foreach (Post::all() as $post)
{
$results[] = [
'id' => $post->id,
'marketname' => $post->subtitle,
];
}
return ['results' => $results];
Note that since the foreach is a oneliner the curly braces are not needed, however most php developers keep the curly braces for readability.
You could also use array_map making the whle expression a oneliner:
return ['results' => array_map(function($post) {
return [
'id' => $post['id'],
'marketname' => $post['subtitle'],
];
}, (array) Post::all())];
Note that I first converted the Eloquent collection to an array. Instead of doing (array) Post::all() you could also do Post::all()->toArray().
The array_map example can be pretified if we use some features from Laravel,
return ['results' => Post::all()->map(function(Post $post) {
return [
'id' => $post->id,
'marketname' => $post->subtitle,
];
})];
Here we used the map method of the Illuminate\Support\Collection object, here you can find some of its documentation.
One warning: it might be slow to return all posts in your database (it of course depends on the size of your project) I would recommend to use pagination when you have more than 25 posts in your table (both for speed and user experience).
See the documentation about pagination for more info.