Search code examples
eloquentlaravel-8belongs-to

Laravel 8 Using Belongs To Failing When Using Where


I know this is me being dumb and not understanding the documentation but I am trying to use the belongsTo feature to access the parent of a class

In the model I have the function defined

class Child extends Model {

    use HasFactory;

    protected $fillable = ['childField'];

    public function parent() {
        return $this->belongsTo(Parent::class, 'parent_id');
    }

}

But I am getting an error when trying to retrieve it in a controller

$child = Child::where('childField', 'ChildTest01')->get();
$parent = $child->parent->parentField;

The where is working because it's returning the right child but I'm getting an error saying that Property [parent] does not exist when trying to get the parent, what am I missing?


Solution

  • In your code, $child is a Collection, not a Model. It should be:

    $child = Child::where('childField', 'ChildTest01')->first();
    $parent = $child->parent->parentField;