Passing data from controller to view in Laravel

VP1234 picture VP1234 · May 13, 2015 · Viewed 114.1k times · Source

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></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)

Answer

Irfan Ahmed picture Irfan Ahmed · May 13, 2015

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);