Reputation: 5609
I have a problem with one to many relationship in Laravel. I cannot retrieve my data from database. My codes are following.
Doctor.php
public function cities()
{
return $this->belongsTo('App\City');
}
City.php
public function doctor()
{
return $this->hasMany('App\Doctor');
}
view
@foreach($doctors as $doctor)
<tr>
<td data-title="ID">{{ $doctor->id }}</td>
<td data-title="Name">{{ $doctor->name }}</td>
<td data-title="Hospital">{{ $doctor->hospital }}</td>
<td data-title="Designation">{{ $doctor->designation }}</td>
<td data-title="City">{{ $doctor->cities->name }}</td> <!-- problem in this line -->
</tr>
@endforeach
When I try to view the data an error has been shown:
ErrorException in 3d7f581c490d492093e6e73f8ebd29525504e56b.php line 46:
Trying to get property of non-object (View: D:\xampp\htdocs\tourisms\root\resources\views\doctors\index.blade.php)
Upvotes: 1
Views: 465
Reputation: 62278
On the belongsTo
side of the relationship, when the foreign key name is not specified, it is built using the name of the relationship. In this case, since your relationship is named cities
, Laravel will look for the field doctors.cities_id
.
If your foreign key is not cities_id
, then you need to either change the name of your relationship method, or specify the name of the foreign key:
public function cities() {
return $this->belongsTo('App\City', 'city_id');
}
// or, better:
public function city() {
return $this->belongsTo('App\City');
}
Also, as mentioned by @Christophvh, the naming of your relationships is a little off, but not programmatically incorrect. It makes more sense and is more readable when belongsTo
/hasOne
relationships are named singular, and belongsToMany
/hasMany
relationships are named plural.
Upvotes: 2
Reputation: 13224
You are trying to loop a Collection and not an array.
2 solutions:
1) add ->get(); when you are calling your relationship in your controller
2)
use
@foreach($doctors->all() as $doctor)
instead of
@foreach($doctors as $doctor)
Also a quick tip: Your naming is not really telling what you are doing. You should swap them around like below. 'A doctor belongs to a city' & 'A city has many doctors'
Doctor.php
public function city()
{
return $this->belongsTo('App\City');
}
City.php
public function doctors()
{
return $this->hasMany('App\Doctor');
}
Upvotes: 1