Foreach in Laravel only returns the first row

I have the following code below in Laravel 7

My controller is picking up the relationship of many to one as per the Model below:

public function listarPermissoes()
    {
        return $this->hasMany(Acoes::class, 'id_permissao','id');
    }

In my controller it looks like this:

public function index()
    {
        $permissoes = Permissoes::all();

        foreach($permissoes as $permissao)
        {
            $permissao->listarPermissoes;
            return $permissao;
        }

    }

The Code return is returning me only the first permission, being that I have multiple permissions in the database. Below follows the example of how it is coming:

{
    "id": 1,
    "value": "Módulo Gerencia de Alunos",
    "list_permissions": [
        {
            "id": 1,
            "value": "Ver dados"
        },
        {
            "id": 2,
            "value": "Listar dados"
        },
        {
            "id": 4,
            "value": "Excluir dados"
        }
    ]
}

The result I seek and bring the following json below:


{
  "id": 1,
    "value": "Módulo Gerencia de Alunos",
    "list_permissions": [
        {
            "id": 1,
            "value": "Ver dados"
        },
        {
            "id": 2,
            "value": "Listar dados"
        },
        {
            "id": 4,
            "value": "Excluir dados"
        }
    ]

},
{
"id": 2,
    "value": "Módulo Gerencia de Turmas",
    "list_permissions": [
        {
            "id": 5,
            "value": "Ver dados"
        },
        {
            "id": 6,
            "value": "Listar dados"
        },
        {
            "id": 7,
            "value": "Excluir dados"
        }
    ]
}
Author: Robson Freitas, 2020-05-26

2 answers

Removes a return... use an echo or look for another way to display. Return cancels the code after the first run.

 -1
Author: Francisco Campos, 2020-05-26 16:53:28

As you are doing by putting the return inside the loop, it is exiting as soon as it performs the first step. If you want to display to the user all the items, I suggest you write using print_r().

 1
Author: Lindolfo Junior, 2020-05-26 18:58:57