skip to Main Content

Using Laravel 10 and trying to get a belongsTo relationship to work and it’s not working. Basically a Fragment has one FragmentGroup while a FragmentGroup has many Fragments.

I’m using it this way and it’s giving me null:

$fragment = Fragment::find(1);
return $fragment->fragmentGroup->name;
class Fragment extends Model {

    public function fragmentGroup(): BelongsTo
    {
        return $this->belongsTo(FragmentGroup:class, 'FragmentID');
    }
}


class FragmentGroup extends Model  {

    public function medicine_type(): HasMany
    {
        return $this->hasMany(Fragment:class, 'FragmentGroupID');
    }
}

Database structure

Fragment:
   FragmentID
   FragmentGroupID
   Name

FragementGroup
   FragmentGroupID
   Name

3

Answers


  1. The way you are using the method is not correct.

    Anyways, to use it you would need to change

    $fragment = Fragment::find(1);
    

    to

    $fragment = Fragment::with('fragmentGroup')->find(1); # or maybe with('fragment_group')
    

    $fragment should now have fragment_group as part of the collection.
    You can check if you dd($fragment);

    If you can see fragment_group but it has blank array/object as its value, then check the methods used inside model.

    Login or Signup to reply.
  2. In your original code, there is a typing mistake in ‘FragmentGroup:class‘. It should be ‘FragmentGroup::class‘.

    Also, you can pass the foreign_key and local_key to further specify.

    Your function should be:

    class Fragment extends Model {
    
        public function fragmentGroup(): BelongsTo
        {
            return $this->belongsTo(FragmentGroup::class, 'FragmentID', 'FragmentGroupID');
        }
    }
    
    
    class FragmentGroup extends Model  {
    
        public function medicine_type(): HasMany
        {
            return $this->hasMany(Fragment::class, 'FragmentGroupID', 'FragmentID');
        }
    }
    

    I think it will be solve your problem.

    Login or Signup to reply.
  3. replace

    $fragment = Fragment::find(1);
    return $fragment->fragmentGroup->name;
    

    to

    $fragment = Fragment::find(1);
    return $fragment->fragmentGroup()->name;
    

    Since fragmentGroup doesn’t load automatically, you should access it not as an attribute (fragmentGroup), but through the fragmentGroup() method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search