[英]how to pass multiple table data to view in laravel 5.2
我的數據庫中有3個表,
用戶模型
public function profiledetails()
{
return $this->hasOne('App\Profiledetails');
}
public function educationHasOne()
{
return $this->hasOne('App\Education');
}
Profiledetails模型
public function user()
{
return $this->belongsTo('App\User');
}
教育模式
public function user()
{
return $this->belongsTo('App\User');
}
我能夠存儲數據。
我想在一個網頁中查看所有表數據,我使用下面的代碼來實現。
public function index()
{
$user = Auth::user()->id;
$profile = array(
User::find($user)->profiledetails,
User::find($user)->educationHasOne
);
return view('profile.index', ['profile' => $profile]);
}
當使用dd($ variablename)時,我可以看到我需要的所有必填字段,
現在,我想知道如何傳遞所有這些數據以在單個頁面中查看。
您可以將數組傳遞給視圖,如下所示:
return view('profile', ['profile' => $profile]);
在視圖中,您可以訪問$profile
。
如果每個都需要此數據,建議使用view composers
。 好的文檔+示例可以在這里找到: https : //laravel.com/docs/5.1/views#passing-data-to-views
感謝@Schellingerht,將數組傳遞給視圖非常完美。
當用戶登錄時,該代碼可以完美運行。
下面是我的代碼
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]);
}
您可以使用@Schellingerht答案,甚至可以使用“緊湊”
$profile= 'someVar';
return view( 'profile',compact('profile') );
在這里,您不需要創建一個assoc數組。 只要確保變量名稱與compact中的字符串相同即可。 在您看來,您只需使用
{{$profile}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.