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'

2

There are 2 answers

0
chanafdo On

The error is because you are using wards() with the parenthesis which will return you the relation not the data itself. Use ward instead without the parenthesis.

And also in your wards table you have a typo. ward_naem should be ward_name

Then change your Bed model to either this

public function ward() // changed from wards to ward
{
    return $this->belongsTo('Wards');
}

or this

public function wards() 
{
    return $this->belongsTo('Wards', 'ward_id'); // added the key
}

Then you can get all the beds with the ward like follows. This is not necessary, but good for performance.

$beds = Beds::with('ward')->get();

Then you can access bed name like follows.

{{ $bed->ward->ward_name }}
0
Amritpal Nagra On

Change the code from

  <td>{{{ $bed->wards()->ward_name}}}</td>

to

  <td>{{{ $bed->wards->ward_name}}}</td>

In fact you should rename wards() method to ward() for clearity as you are getting one instance not instances, because it is belongs to relation.