[英]how to pass multiple table data to view in laravel 5.2
I have 3 tables in database, 我的数据库中有3个表,
User model 用户模型
public function profiledetails()
{
return $this->hasOne('App\Profiledetails');
}
public function educationHasOne()
{
return $this->hasOne('App\Education');
}
Profiledetails model Profiledetails模型
public function user()
{
return $this->belongsTo('App\User');
}
Education model 教育模式
public function user()
{
return $this->belongsTo('App\User');
}
I am able to store the data. 我能够存储数据。
I would like to view all table data in to one single webpage I use the below code to make that happen. 我想在一个网页中查看所有表数据,我使用下面的代码来实现。
public function index()
{
$user = Auth::user()->id;
$profile = array(
User::find($user)->profiledetails,
User::find($user)->educationHasOne
);
return view('profile.index', ['profile' => $profile]);
}
When is use dd($variablename), I am able to see all required field I needed, 当使用dd($ variablename)时,我可以看到我需要的所有必填字段,
Now, I would like to know how to pass all this data to view in single page. 现在,我想知道如何传递所有这些数据以在单个页面中查看。
You can pass an array to the view, like so: 您可以将数组传递给视图,如下所示:
return view('profile', ['profile' => $profile]);
In the view, you can access $profile
. 在视图中,您可以访问$profile
。
If you need this data for each, it's recommend to use view composers
. 如果每个都需要此数据,建议使用view composers
。 Nice documentation + examples can you find here: https://laravel.com/docs/5.1/views#passing-data-to-views 好的文档+示例可以在这里找到: https : //laravel.com/docs/5.1/views#passing-data-to-views
Thanks @Schellingerht, passing an array to the view work perfectly. 感谢@Schellingerht,将数组传递给视图非常完美。
The code works perfect when user is logged in . 当用户登录时,该代码可以完美运行。
Below is my code 下面是我的代码
pass an array to the view
public function index()
{
$user = Auth::user()->id;
$profile = User::find($user)->profiledetails;
$education = User::find($user)->educationHasOne;
return view('profile.index',['profile' => $profile, 'education' => $education]);
} }
you can use @Schellingerht answer or even use "compact" 您可以使用@Schellingerht答案,甚至可以使用“紧凑”
$profile= 'someVar';
return view( 'profile',compact('profile') );
Here you dont need to create an assoc array. 在这里,您不需要创建一个assoc数组。 Just be sure that the variable name is the same as the string in compact. 只要确保变量名称与compact中的字符串相同即可。 in your view you just call it with 在您看来,您只需使用
{{$profile}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.