omrakhur omrakhur - 9 months ago 46
PHP Question

Getting undefined variable in Laravel 5 when passing variable from controller to view

I'm unable to pass my controller variable $sickLeaves to my view, which is reached via index.blade.php of my SickLeaveController (which is a RESTful resource controller).
I keep getting the error: Undefined variable 'sickLeaves'

Here is the routes.php:

Route::group(['middleware' => 'web'], function(){
Route::get('/', 'HomeController@index');
Route::get('auth/logout', 'Auth\AuthController@getLogout');
Route::get('/home', 'HomeController@index');

Here is my SickLeaveController:

class SickLeaveController extends Controller

public function index()

$sickLeaves = SickLeave::all();

return view('sickleaves.index')->with('sickleaves',$sickLeaves);

public function create()
$users = User::pluck('name','id');

return View::make('sickleaves.create')->with('sickleaves',$users);

public function store(Request $request)
$this->validate($request, [
'firstname' => 'required|max:255',
'lastname' => 'required|max:255',
'reason' => 'required|max:255',
'startdate' => 'required',
'status' => 'required',]);

public function show($id)
$sickLeave = SickLeave::find($id);

return View::make('')->with('sickleaves',$sickLeave);

public function edit($id)
$sickLeave = SickLeave::findOrFail($id);

return View::make('sickleaves.edit')->with('sickleaves',$sickLeave);

public function update(Request $request, $id)

public function destroy($id)
$sickLeave = SickLeave::findOrFail($id);

Session::flash('Item successfully deleted');
return redirect()->route('sickleave.index');

Here is the index.blade.php:

@foreach($sickLeaves as $sickLeave)
<td style="width: 8%">{{ $sickLeave->id }}</td>
<td style="width: 12%"><span class="fw-semi-bold">{{ $sickLeave->firstname }}</span></td>
<td style="width: 12%"><span class="fw-semi-bold">{{ $sickLeave->surname }}</span></td>
<td class="no-sort hidden-xs" style="width: 12%">{{ $sickLeave->reason }}</td>
<td class="hidden-xs">{{ $sickLeave->startdate }}</td>
<td class="hidden-xs">{{ $sickLeave->enddate }}</td>
<td class="no-sort">{{ $sickLeave->status }}</td>
<td class="no-sort"><div class="btn-group">
<button class="btn btn-inverse">Actions</button>
<button class="btn btn-inverse dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-caret-down"></i>
<ul class="dropdown-menu">
<li><a href="{{ route('', $sickLeave->id) }}">View Details</a></li>
<li><a href="{{ route('sickleaves.edit', $sickLeave->id) }}">Edit</a></li>
<li class="divider"></li>
<li><a href="#">Delete</a></li>

Answer Source

PHP variables are case sensitive!

You passing sickleaves, but in view You are trying to get sickLeaves, that is the problem.