Foreach in Laravel only returns the first line

Asked

Viewed 172 times

0

I got Following code down on Laravel 7

My controller is taking the many relationship to one as per the model below:

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

On my controller it’s like this:

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

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

    }

The return of the code is returning me only the first permission, and I have several 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"
        }
    ]
}

2 answers

1

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

-1


Remove the Return... use an echo or look for another way to display. Return cancels the code after the first execution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.