簡體   English   中英

Laravel 5.7如何從Controller show($ id)函數獲取數據? 二手查詢生成器

[英]Laravel 5.7 How to get data from Controller show($id) function? Used Query builder

StaffController

public function show($id){
  $staffinfo = DB::table('staff')->where('user_id', $id)->get();
  return view('staff.view')->with('staffinfo', $staffinfo); 
}

view.blade.php

<h1>{{$staffinfo->name}}</h1>
<p>{{$staffinfo->user_id}}</p>

通過show($id)函數在視圖中show($id)人員表中的數據是否正確?

出現錯誤:

“此集合實例上不存在屬性[名稱]。(查看:F:\\ xampp \\ htdocs \\ gchsc \\ resources \\ views \\ staff \\ view.blade.php)”

->get()切換到->first() $staffInfo是數據庫記錄的Collection ,而不是單個記錄:

StaffController.php

$staffinfo = DB::table('staff')->where('user_id', $id)->first();

然后,以下將在您看來有效:

staff/view.blade.php

<h1>{{ $staffinfo->name }}</h1>
<p>{{ $staffinfo->user_id }}</p>

或者,保留您的代碼不變並在視圖中進行迭代:

StaffController.php

$staffinfo = DB::table('staff')->where('user_id', $id)->get();

staff/view.blade.php

@foreach($staffInfo AS $staff){
  <h1>{{ $staff->name }}</h1>
  <p>{{ $staff->user_id }}</p>
@endforeach

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM