Home > database >  Pass data from controller to View in Laravel
Pass data from controller to View in Laravel

Time:03-14

I have a query that I am not able to pass to the view.

$dias_usados = calendario::where('id_funcionario', '=', $userid)
    ->groupBy('id_funcionario')
    ->sum('contaferias');

dd outputs the correct expected value.

I tried to pass to the View as follows:

return view(
    'ausencia',
    compact('tabela'),
    ['itens' => $ferias],
    ['dias_usados' => $dias_usados]
);

I'm having problems with the last one dias_usados. The first two work normally.


<h3>{{$dias_usados}}</h3>

Causes the following error:

Undefined variable: "dias_usados"


I also leave the path I have on the route, but I don't see anything wrong

Route::get('Ausencia', [AusenciaController::class, 'index'])->name('ausencia.index');

CodePudding user response:

This is the the definition of the view helper

function view($view = null, $data = [], $mergeData = []) { }

You are misusing the function by giving it three separate arrays expecting it to get them as $data.

Fixes

return view('ausencia', [
    'tabela' => $tabela,
    'itens' => $ferias,
    'dias_usados' => $dias_usados,
]);
return view('ausencia')
    ->with(compact('tabela'))
    ->with(['itens' => $ferias])
    ->with(['dias_usados' => $dias_usados]);
return view(
    'ausencia',
    array_merge(
        compact('tabela'),
        ['itens' => $ferias],
        ['dias_usados' => $dias_usados]
    )
);
  • Related