首页 文章

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

提问于
浏览
12

嘿伙计们我是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)

6 回答

  • -5

    你也可以尝试这个:

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

    并在view.blade文件中使用此变量来获取学生姓名和其他列:

    {{$students['name']}}
    
  • 0

    我认为从控制器传递数据到视图是不好的 . 因为它不可重复使用并使控制器变得更胖 . 视图应分为两部分:模板和帮助程序(可以从任何地方获取数据) . 您可以搜索 view composer in laravel 以获取更多信息 .

  • 8

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

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

    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 }} 这样的变量 .

  • 1

    在Laravel 5.6中:

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

    你能尝试一下吗?

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

    试试这段代码:

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

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

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

相关问题