Reputation: 95
How can I get or display company column from contractors table to put it in my blade? I already try figured it out by using hasManyThrough relationship but it doesn't work since all example that I made reference to is not having the same flow with me.
contractors table
id
company
residentials table
id
contractor_id
buyers table
id
residential_id
This is the Model
Contractor.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contractor extends Model
{
protected $table = 'contractors';
protected $fillable = ['user_id','company','address','phone_no','email','avatar'];
public function residential()
{
return $this->hasMany(Residential::class);
}
public function buyers()
{
return $this->hasManyThrough('App\Buyer', 'App\Residential');
}
public function buyer()
{
return $this->hasOneThrough('App\Buyer', 'App\Residential');
}
}
If I do this kind of code, it will be $contractor->buyer. While I want it to be $buyer->contractor->company
Buyer.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Buyer extends Model
{
protected $fillable = ['buyer_id', 'name', 'address', 'phone_no', 'email', 'avatar', 'user_id', 'residential_id'];
public function residential()
{
return $this->belongsTo(Residential::class);
}
}
Residential.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Residential extends Model
{
protected $fillable = ['name','res_code','postcode','city','state','image','contractor_id'];
public function contractor()
{
return $this->belongsTo(Contractor::class);
}
public function buyer()
{
return $this->hasMany(Buyer::class);
}
}
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]);
}
This is the view that I'm working on and there is no looping since this is a profile for buyers login.
index.blade.php
<h4 class="heading"><b><center>Buyer'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>Residence: </b>{{$buyer->residential->name}}</li>
<li><b>Phone Number: </b>{{$buyer->phone_no}}</li>
<li><b>Email: </b>{{$buyer->email}}</li>
<li><b>Contractor: </b>{{$buyer->contractor->company}}</li>
</ul>
Based on the above view code, I already did the the relationship for Residence: But I'm not able to do it for Contractor: I hope there is someone to help me.
Upvotes: 0
Views: 744
Reputation: 160
In controller
$buyers = Buyer::where('user_id', '=', Auth::id())->first();
return view('buyers.index',['buyer'=>$buyers]);
then call in blade file
$buyers->residential->contractor->company
Upvotes: 0
Reputation: 12391
try this
then u can do
$buyer->contractor->company
to
$buyer->residential->contractor->company
u have alredy added belongsTo
added to 2 model
Upvotes: 0