dai007uk dai007uk - 2 years ago 87
SQL Question

Laravel Model/View Relationship

I am learning Laravel and just can't understand how to solve the below issue.

I have two tables (ofcourse not databases) :)

Table: Birds

Table: Eggs

Sample Data:

id 1
name Jeff

id 1
parent_id 1

I have two models which are Bird and Egg
I am simply displaying the data which is available in the database (MySQL).


@foreach ($eggs as $egg)
..form data
{{ $egg->id }}
{{ $egg->parent_id }}
..end of form

This works all fine. However I wish to show the name of the parent (bird) instead of the id. (so from the sample data it will show Jeff)

I have tried using this in the models

return $this->belongsTo('Bird'); //in Egg Model
return $this->belongsTo('Egg'); //in Bird Model

Would be really grateful for any help/explanation regarding this.

Answer Source

In your Egg model you need to setup the relationship like so:

public function bird()
    return $this->belongsTo(Bird::class,'parent_id');

If your column would have been bird_id it would have found the foreign key column on it's own however since it automatically tries the model name appended with _id it doesn't know which column to use. But you can directly specify the column that references the primary key of Bird with the second parameter in belongsTo().

Once you do this you will simply be able to reference the relationship like so:

{{ $egg->bird->name }}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download