如何在Laravel的View方法中传递变量

时间:2019-01-28 13:43:33

标签: laravel view subdomain

如何传递一个可以由Laravel中的view()方法解析的变量?

  public function index($department_id) { 

     $employees=Employee::all();  
     $department=Department::find($department_id); 

     return view('departments.$department->department_code.index')->with('department',$department)->with('employees', $employees); 
  }

这个想法是,每个部门都有一个部门文件夹,其名称与部门模型中的department_code相同。我希望能够接收department_id,检索正确的部门,然后返回具有部门所有属性的适当视图。

当我尝试这样做时,出现此错误InvalidArgumentException View [departments.$department->department_code.index] not found.

3 个答案:

答案 0 :(得分:2)

return view(sprintf('departments.%s.index', $department->department_code), [
    'departments' => $departments,
    'employees' => $employees,
]);

答案 1 :(得分:0)

如果要在字符串中使用内联变量,则需要使用双引号(")。

return view("departments.$department->department_code.index")->with('department',$department)->with('employees', $employees);

答案 2 :(得分:0)

您可以这样做:

return view("departments.$department->department_code.index", compact('employees','department'))