I am trying to make relation between two models named as Wards and Beds. Table structure of ward is
id | ward_naem| ward_type
1 | ENT | male
2 | Heart | male
Table of beds is
id | ward_name| ward_id
1 | 3 | 1
2 | 3 | 1
2 | 2 | 2
Relationship in Beds Model is
public function wards()
{
return $this->belongsTo('Wards');
}
Relations is Wards model is
public function beds()
{
return $this->hasMany('Beds');
}
In my controller i am writing these lines
public function index()
{
$beds = Beds::all();
return \Illuminate\Support\Facades\View::make('adminipd.index',compact('beds'));
}
and when it redirect to index with object named beds I am retrieving ward_name with object of $beds as
<td>{{{ $bed->wards()->ward_name}}}</td>
<td>{{{ $bed->bed_no }}}</td>
It doesn't work and gives a blank page if I remove this line
<td>{{{ $bed->wards()->ward_name}}}</td>
it works fine for "bed_no". In log file of my laravel project i got an error which is
ERROR: exception 'ErrorException' with message 'Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$ward_name'
The error is because you are using
wards()with the parenthesis which will return you the relation not the data itself. Usewardinstead without the parenthesis.And also in your
wardstable you have a typo.ward_naemshould beward_nameThen change your
Bedmodel to either thisor this
Then you can get all the beds with the ward like follows. This is not necessary, but good for performance.
Then you can access bed name like follows.