Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

raygun's avatar

Whats's the proper way to loop through an array for an api in laravel 5.1

Hello fellow programmers I am trying to loop through an array. I have experimented a bit but it's not working properly. it outputs.but it doesn't loop through everything I have in my database. this is my code for my ApiController

<?php

namespace App\Http\Controllers;

use App\Post;
use App\Http\Requests;

class ApiController extends Controller
{
    public function index()
    {
        foreach (Post::all() as $post )

        return array(
            'results' => [
                array('id' =>$post->title,
                    'marketname' => $post->subtitle),
             
            ]
        );
    }
}

also the curly bracket just before last is highlighted in my editor. When I hover over it, it says it's expecting a return. But if I move the return to where it says it should be, I get no output. To be clear I want to display something like this

"results": [
{
"id": "1002336",
"marketname": "0.2 Harvest Home Echo Park Market"
},
{
"id": "1006207",
"marketname": "0.3 Echo Park Market"
},
{
"id": "1003343",
"marketname": "0.4 La Familia Verde Farmers Market"
},

any help would be greatly appreciated

0 likes
4 replies
thomaskim's avatar
Level 41

@raygun A return statement basically ends that method. When you're looping and then you "return" something in the middle of it, that method is over and the loop ends.

With that said, is this what you're trying to do?

  1. Get all posts
  2. Only get their title and subtitle
  3. Use their title as the id and their subtitle as marketname

If that's what you're trying to do, then I believe you can just do this. It's a lot cleaner too. :)

public function index() {
    return Post::get(['title as id', 'subtitle as marketname']);
}
1 like
MarkRedeman's avatar

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.

1 like

Please or to participate in this conversation.