如何从多个表中获取数据并使用laravel中的“ - > with()”发送到html

时间:2017-05-24 17:37:47

标签: php html mysql laravel

我需要表'用户'和'部门',我想从两个表中获取数据并以html格式输入。 这是我的代码无法正常工作,因为它中缺少一些东西。 这是控制器的代码:

 public  function showProfileForm($id){
    $user = DB::table('users')->where('id','=',$id)->get();

    $dpt = DB::table('departments')->orderBy('department_name','asc')->get();
    return view('profile.showProfile')->with(['selDpt', $dpt, 'user', $user]);
}

3 个答案:

答案 0 :(得分:2)

get()方法将数据检索为多维数组。因此,当您只检索一个数组时,您必须在查询结束时使用first()方法。所以只需从

更改查询
$user = DB::table('users')->where('id','=',$id)->get();
to 
$user = DB::table('users')->where('id','=',$id)->first();

现在,您必须按array传递数据。所以只需更改行

return view('profile.showProfile')->with(['selDpt', $dpt, 'user', $user]);
To
return view('profile.showProfile')->with(['selDpt' => $dpt, 'user' => $user]);

shoProfile.blade.php

你必须使用$selDpt& $user变量用于使用或回显数据。 希望它会奏效。

https://laravel.com/docs/5.4/views#passing-data-to-views

了解详情

答案 1 :(得分:0)

您可以使用此语法将多个变量传递给视图:

return view('profile.showProfile', [
    'selDpt' => $dpt,
    'user' => $user
]);

https://laravel.com/docs/5.4/views#passing-data-to-views

答案 2 :(得分:0)

或者您可以使用PHP函数compact()http://php.net/compact

$user = DB::table('users')->where('id','=',$id)->get();
$dpt = DB::table('departments')->orderBy('department_name','asc')->get();

return view('profile.showProfile', compact('dpt', 'user'));

您的视图中会有$user$dpt