2015-05-13 25 views
10

嗨,我是laravel的新手,我一直試圖將表'student'的所有記錄存儲到變量中,然後將該變量傳遞給視圖以便我可以顯示它們。從控制器傳遞數據在Laravel中查看

我有一個控制器 - 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)

回答

11

你可以試試看,

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

不,不工作:( – VP1234

+0

你會得到同樣的錯誤? –

+0

是的,undefined變量學生 – VP1234

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

用於傳遞單個變量以查看。

裏面你的控制器創建這樣的方法:

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

在您的路線

Route::get('/sleep', '[email protected]'); 

在你看來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中搜索查看作曲家以獲得更多信息。

相關問題