【问题标题】:How to pass an object to a view in Laravel?如何将对象传递给 Laravel 中的视图?
【发布时间】:2016-12-11 19:45:03
【问题描述】:

我想将 Student Model 的对象传递给 Laravel 中的视图。我尝试使用

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

其中 $student 是学生模型的一个实例(代码如下)

但它给出了错误“非法偏移类型”

我知道数据可以作为数组传递给视图。但如果可能的话,我真的想把它作为一个对象传递。然后我可以通过从get方法中获取数据来显示数据如下。

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

我正在寻找一种可以使用保留对象而不是数组来完成的解决方案。(如果可能的话)

Student 模型代码如下。它由简单的 setter 和 getter 组成。

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

【问题讨论】:

    标签: php laravel object view laravel-5


    【解决方案1】:

    您有多种选择

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

    【讨论】:

      【解决方案2】:

      你必须为你的变量命名:

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

      【讨论】:

      • 非常感谢
      猜你喜欢
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多