在Laravel中将数据从控制器传递到视图

2022-08-30 16:26:36

我是Laravel的新手,我一直在尝试将表“student”的所有记录存储到一个变量中,然后将该变量传递给视图,以便我可以显示它们。

我有一个控制器 - ProfileController和里面的一个函数:

public function showstudents() {
    $students = DB::table('student')->get();
    return View::make("user/regprofile")->with('students',$students);
}

在我看来,我有这个代码:

<html>
    <head>
        //---HTML Head Part
    </head>
    <body>
        Hi {{ Auth::user()->fullname }}
        @foreach ($students as $student)
            {{ $student->name }}
        @endforeach
        @stop
    </body>
</html>

我收到此错误:Undefined variable: students (View:regprofile.blade.php)


答案 1

你能试一试吗,

return View::make("user/regprofile", compact('students')); OR
return View::make("user/regprofile")->with(array('students'=>$students));

虽然,您可以设置多个变量,如下所示,

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

答案 2

用于传递要查看的单个变量。

在控制器内部创建一个方法,如下所示:

function sleep()
{
        return view('welcome')->with('title','My App');
}

在您的路线中

Route::get('/sleep', 'TestController@sleep');

在您的视图中 。您可以像这样回显您的变量Welcome.blade.php{{ $title }}

对于数组(多个值)更改,睡眠方法为:

function sleep()
{
        $data = array(
            'title'=>'My App',
            'Description'=>'This is New Application',
            'author'=>'foo'
            );
        return view('welcome')->with($data);
}

您可以像 .{{ $author }}


推荐