在Laravel中使用index.blade中的多态关系

Use polymorphic relation in index.blade in Laravel

在此之前,我没有使用多态关系。我只对每个 table 使用 user_id,例如 Admin、Buyer 和 Contractor,以便将其与用户 table 相关联。现在,我可以使用多态关系,因为我需要使用导航栏中那 3 个 table 中的 nameavatar 列。每次用户登录他们的帐户时,他们都会在导航栏上看到他们的名字和头像。

用户table

id
role
email
typable_id
typable_type

买家table

id 
name
address
phone_no
email
avatar

User.php

public function typable()
    {
        return $this->morphTo();
    }

Buyer.php

public function user()
    {
        return $this->morphMany(User::class, 'typable');
    }

这已经解决了我的问题。但是现在的问题是,如何为索引视图使用多态关系?这是我使用 user_id.

时使用的先前查询

BuyerController.php

public function index(Request $request)
    {
        if(Auth::user()->role == 'buyer')
            {     
                $buyers = Buyer::where('user_id', '=', Auth::id())->first();
                return view('buyers.index',['buyer'=>$buyers]);
            }
    }

index.blade.php

<div class="profile-main">
    <img src="http://localhost:8000/storage/images/{{auth()->user()->typable->avatar}}" width="100" length="100" class="img-circle" alt="Avatar">
    <h3 class="name">{{$buyer->name}}</h3>
</div>

<div class="profile-detail">
   <div class="profile-info">
       <h4 class="heading"><b><center>Resident's Details</center></b></h4>
           <ul class="list-unstyled list-justify">
               <li><b>Buyer ID: </b>{{$buyer->buyer_id}}</li>
               <li><b>Name: </b>{{$buyer->name}}</li>
               <li><b>Address: </b>{{$buyer->address}}</li>
               <li><b>Phone Number: </b>{{$buyer->phone_no}}</li>
               <li><b>Email: </b>{{$buyer->email}}</li>
            </ul>
    </div>
<div class="text-center"><a href="/buyer/{{$buyer->id}}/edit" class="btn btn-primary">Edit Profile</a></div>                       

当我使用买家帐户登录时,这是我得到 SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from buyerswhereuser_id = 8 limit 1)Trying to get property 'name' of non-object 的错误。

试试这个:


$buyers = Buyer::find(Auth::user()->typable_id);