How to get the default $id from another table using laravel model relationship?

Viewed 46

I am facing the problem whereby I don't know the syntax of letting the id of my property model equals to property_id value in property_doc table.

In PropertyDoc model

public function property()
{
    return $this->belongsTo(Properties::class, 'property_id');
}

In Properties model

public function property_id()
{
    return $this->hasMany(PropertyDoc::class, 'property_id');
}

In PropertyController

public function StoreInfoProperty(Request $request)
{
    $propertyInfo = new PropertyDoc;
    $propertyInfo->property_id = $property_id;
}

I am stuck at retrieving the default id value in properties database to be equal to the property_id in property_docs database. Thank you.

1 Answers

You should change the naming of the relationship, see my example below:

In Properties model

public function propertyDocs()
{
    return $this->hasMany(PropertyDoc::class, 'property_id', 'id');
}

In PropertyDoc model

public function property()
{
    return $this->belongsTo(Properties::class, 'property_id', 'id');
}

In controller

public function StoreInfoProperty(Request $request)
{
    $propertyDoc = PropertyDoc::with(['property'])->where('...logic here');

    $property_id = $propertyDoc->property->id;

}

hope can help you and happy coding !

Related