Reputation: 494
I'm getting Undefined Variable error. Here is my controller:
Controller:
public function index()
{
/**$englishgrades = StudentHistory::select('date', 'student_id', 'grade')
->where('subject', 'English')
->groupBy('student_id')
->orderBy('date','desc')
->first()
->get();
*/
$englishgrades = StudentHistory::where('subject', 'English')
->get();
$englishgrades = [];
return view('home', $englishgrades);
}
I'm calling it to my blade using
{{ $englishgrades }}
Undefined variable: englishgrades (View: /home/vagrant/Code/projects/DYK/resources/views/home.blade.php)
Upvotes: 1
Views: 445
Reputation: 1829
return view('home', $englishgrades);
in above code second Argument is need to be a array key as a variable name and value as variable or value.
like
return view('home',['englishgrades'=>$englishgrades]);
you can write by hand or use compact function to generate a array() of key value pair
return view('home',compact('englishgrades'));
So Now you access a $englishgrades
in a View
or you can use like
$data = compact('englishgrades'); or
$data = ['englishgrades'=>$englishgrades];
return view('home',$data);
here main thing is In View you use key as a variable ex:
$data = ['grades'=>$englishgrades];
return view('home',$data);
So in View you have to use $grades
Upvotes: 1
Reputation: 3009
Remove your
$englishgrades = [];
and
return view('home', ['englishgrades' => $englishgrades]);
Upvotes: 1
Reputation: 1672
you should use compact
$englishgrades = StudentHistory::where('subject', 'English')
->get();
$englishgrades = []; // remove this so it will not overwrite the above declaration ..
return view('home', compact('englishgrades'));
it will return an empty array since you're overwriting the original value ..
Upvotes: 1