2016-12-11 42 views
1

我想將學生模型的對象傳遞給Laravel中的視圖。我試着用如何將對象傳遞給Laravel中的視圖?

return view('student/main')->with($student); 

其中$學生是學生模型(代碼如下)

的實例,但它給了一個錯誤「非法偏移類型」

我知道,數據可以作爲傳遞一個數組到視圖。但如果可能的話,我真的想把它作爲一個對象來傳遞。然後,我可以通過從get方法獲取數據來顯示數據。

<h4 class="text-left"><strong>{{$student->getName()}}</strong> </h4> 

我正在尋找可保持使用對象而不是數組來完成的解決方案。(如果可能)

學生模型代碼如下。它由簡單的制定者和獲得者組成。

class Student extends Model{ 

//attributes 

private $student_id; 
private $first_name; 
private $last_name; 
private $batch_id; 

// set attributes 

public function setID($student_id) 
{ 
    $this->student_id = $student_id; 
} 

public function setFirstName($first_name) 
{ 
    $this->first_name = $first_name; 
} 

public function setLastName($last_name) 
{ 
    $this->last_name = $last_name; 
} 

public function setBatchID($batch_id) 
{ 
    $this->batch_id = $batch_id; 
} 

// get attributes 

public function getName() 
{ 
    return $this->first_name." ".$this->last_name; 
} 

public function getID() 
{ 
    return $this->student_id; 
} 

public function getBatchID() 
{ 
    return $this->batch_id; 
} 

回答

1

你必須命名您的變量:

return view('student/main')->with(['student' => $student]); 
2

你有多項選擇做

return view('student/main', ['student'=> $student]); 

return view('student/main', compact('student')); 

return view('student/main')->with('student', $student); 

return view('student/main')->withStudent($student);