I am new to Laravel and I have been trying to store all records of table 'student' to a variable and then pass that variable to a view so that I can display them.
I have a controller - ProfileController and inside that a function:
public function showstudents() {
$students = DB::table('student')->get();
return View::make("user/regprofile")->with('students',$students);
}
In my view, I have this code:
<html>
<head>
//---HTML Head Part
</head>
<body>
Hi {{ Auth::user()->fullname }}
@foreach ($students as $student)
{{ $student->name }}
@endforeach
@stop
</body>
</html>
I am receiving this error: Undefined variable: students (View:regprofile.blade.php)
Just pass it as an array: $data = [ 'name' => 'Raphael', 'age' => 22, 'email' => '[email protected]' ]; return View::make('user')->with($data); Or chain them, like @Antonio mentioned. The recommended way is to use compact method to pass variables.
In real applications, controller render response using views which are defined outside the controllers. These views are located at /resources/views folder of your Laravel application. After a controller has done its working e.g. interaction with model etc. Controller select a view and send its contents to browser.
Can you give this a try,
return View::make("user/regprofile", compact('students')); OR
return View::make("user/regprofile")->with(array('students'=>$students));
While, you can set multiple variables something like this,
$instructors="";
$instituitions="";
$compactData=array('students', 'instructors', 'instituitions');
$data=array('students'=>$students, 'instructors'=>$instructors, 'instituitions'=>$instituitions);
return View::make("user/regprofile", compact($compactData));
return View::make("user/regprofile")->with($data);
For Passing a single variable to view.
Inside Your controller create a method like:
function sleep()
{
return view('welcome')->with('title','My App');
}
In Your route
Route::get('/sleep', 'TestController@sleep');
In Your View Welcome.blade.php
. You can echo your variable like {{ $title }}
For An Array(multiple values) change,sleep method to :
function sleep()
{
$data = array(
'title'=>'My App',
'Description'=>'This is New Application',
'author'=>'foo'
);
return view('welcome')->with($data);
}
You can access you variable like {{ $author }}
.
The best and easy way to pass single or multiple variables to view from controller is to use compact() method.
For passing single variable to view,
return view("user/regprofile",compact('students'));
For passing multiple variable to view,
return view("user/regprofile",compact('students','teachers','others'));
And in view, you can easily loop through the variable,
@foreach($students as $student)
{{$student}}
@endforeach
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With