简体   繁体   中英

Use polymorphic relation in index.blade in Laravel

Before this, I do not use polymorphic relation. I only use user_id for each table such as Admin, Buyer and Contractor to relate it with User table. Now, I'm able to use polymorphic relation since I need to use name and avatar column from those 3 tables in navigation bar. Every time the users login into their account, they will see their name and avatar on the navigation bar.

user table

id
role
email
typable_id
typable_type

buyers 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');
    }

That's already fixed my problem. But the problem now, how can I use polymorphic relation for my index view? This is the previous query that I use when I used 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>                       

When I login using the buyer's account, this is the error that I got SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from buyers where user_id = 8 limit 1) and Trying to get property 'name' of non-object .

尝试这个:


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM