Search code examples
phparrayslaravelviewcontroller

trying to pass array in the view with error in the third


service one and two I can receive in the view but the third gives an error

Controller:

    $servicos1 = DB::select("select * from servicos WHERE categoria = 1 ORDER BY servico DESC");

    $servicos2 = DB::select("select * from servicos WHERE categoria = 2 ORDER BY servico DESC");

    $servicos3 = DB::select("select * from servicos WHERE categoria = 3 ORDER BY servico DESC");

    return view('adm.servico', ['servicos1' => $servicos1], ['servicos2' => $servicos2], ['servicos3' => $servicos3]);

View:

ErrorException Undefined variable: servicos3 (View: C:\Users\Vivere\Documents\Code\congregacao\resources\views\adm\servico.blade.php)

When I change the order, the error shows problem in the last one

Controller:

    $servicos1 = DB::select("select * from servicos WHERE categoria = 1 ORDER BY servico DESC");

    $servicos2 = DB::select("select * from servicos WHERE categoria = 2 ORDER BY servico DESC");

    $servicos3 = DB::select("select * from servicos WHERE categoria = 3 ORDER BY servico DESC");

    return view('adm.servico', ['servicos1' => $servicos1], ['servicos3' => $servicos3], ['servicos2' => $servicos2]);

View:

ErrorException Undefined variable: servicos2 (View: C:\Users\Vivere\Documents\Code\congregacao\resources\views\adm\servico.blade.php)

When I delete the third item and leave service 1 and service 2 everything works

View:

@foreach ($servicos1 as $item)

{!! $item->servico !!}                          

@endforeach

@foreach ($servicos2 as $item)

{!! $item->servico !!}                          

@endforeach





But I need to pass all three, help me!

Solution

  • In Laravel, the reason why the code doesn't work is because of the way the variables are being passed to the view. The view() method expects all the variables to be grouped into a single array, and you are sending multiple arrays separately. The correct way is to combine all the variables into a single array, as in the example below:

    return view('adm.servico', [
        'servicos1' => $servicos1,
        'servicos2' => $servicos2,
        'servicos3' => $servicos3
    ]);