Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel belongsTo not returning any values

I have a class called Dbc which has ‘links’ attached to it called DbcLink.
Each link had a ‘type’ (DbcLinkType)

I’m returning the links attached to the Dbc fine

 class Dbc extends Model
   {
    use HasFactory;

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function links($filter = NULL)
    {
        return $this->hasMany(DBCLink::class);
    }
   }

$social = $dbc->links()->first();
dd($social);

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but when I try and get the ‘link type from those links it returns an empty list

class DbcLink extends Model
 {
    use HasFactory;

    public function dbc()
    {
        return $this->belongsTo(Dbc::class);
    }

    public function link_type()
    {
        return $this->belongsTo(DbcLinkType::class);
    }
 }

$social = $dbc->links()->first();
dd($social->link_type()->get());

enter image description here

dbc_links table

enter image description here

dbc_link_types table

enter image description here

Any suggestions as to why its returning an empty list?

>Solution :

When invoking the link_type method, Eloquent will attempt to find a DbcLinkType model that has an id which matches the link_type_id column on the DbcLink model.

Eloquent determines the foreign key name by examining the name of the relationship method and suffixing the method name with _id.
1

Rename your relation method from link_type to dbc_link_type so that it looks up dbc_link_type_id column on the DbcLink model.

Alternately, you can inform Eloquent to find the DbcLinkType model that has an id which matches the dbc_link_type_id column on the DbcLink model.

You can accomplish that by specifying the foreignKey when defining the relation;

        return $this->belongsTo(DbcLinkType::class, 'dbc_link_type_id');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading