问题 将数据从控制器传递到Laravel中的视图


嘿伙计我是laravel的新手,我一直试图将表'student'的所有记录存储到变量中,然后将该变量传递给视图,以便我可以显示它们。

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

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

在我看来,我有这个代码

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

    @endforeach


    @stop

    </body>
    </html>

我收到此错误:未定义的变量:学生(查看:regprofile.blade.php)


6747
2018-05-13 16:29


起源



答案:


你能尝试一下吗?

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

12
2018-05-13 16:40



不,不工作:( - VP1234
你得到同样的错误吗? - Irfan Ahmed
是的,未定义的变量学生 - VP1234
哎呀我在紧凑('学生')之后缺少一个支架。谢谢 - VP1234


答案:


你能尝试一下吗?

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

12
2018-05-13 16:40



不,不工作:( - VP1234
你得到同样的错误吗? - Irfan Ahmed
是的,未定义的变量学生 - VP1234
哎呀我在紧凑('学生')之后缺少一个支架。谢谢 - VP1234


用于传递单个变量以进行查看。

在您的控制器内创建一个方法,如:

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 }}


8
2018-01-04 10:35



更精心的回答。 - rahul


在Laravel 5.6中:

$variable = model_name::find($id);
return view('view')->with ('variable',$variable);

1
2017-08-02 13:57





试试这段代码:

return View::make('user/regprofile', array
    (
        'students' => $students
    )
);

或者,如果要将更多变量传递到视图中:

return View::make('user/regprofile', array
    (
        'students'    =>  $students,
        'variable_1'  =>  $variable_1,
        'variable_2'  =>  $variable_2
    )
);

0
2018-05-14 08:46





我认为从控制器到视图的传递数据很糟糕。因为它不可重复使用并使控制器更加丰富。视图应分为两部分:模板和帮助程序(可以从任何地方获取数据)。你可以搜索 在laravel中查看作曲家 获得更多信息。


-5
2017-07-03 02:49