I am unable to set up eloquent relationship on the default User model.Spare table has a foreign key which is UserID referencing User table. Following is the code
User.php
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function isAdmin()
{
return $this->type; // this looks for an admin column in your users table
}
public function spares()
{
return $this->hasMany('App\Spares');
}
}
Spare.php
public function user()
{
return $this->belongsTo('App\User');
}
SearchController.php
public function index(Request $request)
{
$spares=Spares::with('user','model')
->where ('description','LIKE','%'.$request->searchName.'%')
->paginate(5);
return View::make('browse')->with('spares', $spares);
}
browse.blade.php cannot access {{$spare->user->name }}
@foreach($spares as $spare)
<tr>
<td class="col-md-6">
<div class="media">
<a class="thumbnail pull-left" href="#"> <img class="media-object"
src='{{ asset("images/spares/$spare->imagePath") }}'
tyle="width: 100px; height: 100px;padding-left: 10px"> </a>
<div class="media-body" style="padding-left: 10px;">
<h4 class="media-heading"><a href="#">{{$spare->description}}</a></h4>
<h5 class="media-heading"> by <a href="#">{{$spare->user->name }}</a></h5>
</div>
</div>
</td>
<td class="col-md-1 text-center"><strong>Rs. {{$spare->price}}/=</strong></td>
</tr>
@endforeach
following is the error
In reply to your comment:
spares table is 'spares' in that foreign key is 'retailer_id' which references the User table
From the documentation:
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Spare model is not user_id, you may pass a custom key name as the second argument to the belongsTo method:
public function user()
{
return $this->belongsTo('App\User', 'retailer_id');
}
However, it's probably better to make Eloquent just succeed in resolving your relation without any override when not necessary. One way is to rename your method in Spare.php:
public function retailer()
{
return $this->belongsTo('App\User');
}
Another would be to leave that method as is and rename the foreign key column name to user_id
. But you'll of course lose the semantics of the word retailer
in this case.