Vijayanand Premnath
Vijayanand Premnath

Reputation: 3605

Laravel column name and relationship name same

Can I have column name and relationship name same?

example:

I have a column edited_by in mack.php model and I want to get full details of user mentioned in edited_by from users table so i have relationship like below

public function edited_by(){
        return $this->hasOne('App\User','id','edited_by');
    }

now, if i try to access $model->edited_by->first_name its throwing error 'trying to get property of non-object'

is there any way to fix it other than having different names?

Upvotes: 6

Views: 6426

Answers (2)

MrEduar
MrEduar

Reputation: 1931

You can achieve this by explicitly calling the relationship method using the getRelation method on the model. This way, you can make sure you are accessing the relationship and not the column directly. Here's how you can do it:

// Assuming $model is an instance of the Mack model
$editedByRelation = $model->getRelation('edited_by');

// Now you can access the properties of the related User model
if ($editedByRelation) {
    $firstName = $editedByRelation->first_name;
    // Do whatever you need with $firstName
} else {
    // Handle the case where the relationship is not loaded
}

Upvotes: 1

Reena
Reena

Reputation: 291

The short answer is no. You can't have them be the same name because the column will always be returned if found and the relationship will never be returned if a column is found with that name.

Changing the column name to user_id would be more appropriate than edited_by. It's more descriptive, and it's also the default id that Eloquent will look for. Similarly the relationship name makes more sense being named user() rather than edited_by() because it returns a user Model.

The slightly longer, and totally incorrect answer is that you can access the relationship with $model->edited_by()->first_name this will result in extra queries being run unnecessarily though.

Upvotes: 9

Related Questions