Column name and relationship name same

Published 1 year ago by lorvent

Hello,

Can i have column name and relationship name same?

ex:

I have a column edited_by in Abc.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?

Best Answer (As Selected By lorvent)
nickwest

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.

nickwest

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.

lorvent
lorvent
1 year ago (13,385 XP)

Hi, Thanks for the response.

I already have some other user columns so this one has to be a different, ofcourse i can append _id to make it something like edited_by_id() as relationship name.

$model->edited_by()->first_name is not working, its throwing some other error.

nickwest

I'm surprised $model->edited_by()->first_name throws an error, it's not the right thing to do anyway. edited_by_id would be more appropriate than edited_by then. I'm assuming you have mutliple users attached to the Model? Makes sense to name them based on type or function in that case, but appending _id would still be recommended. Since it is an id column. And that does free up the relationship name for you then too.

Personally, I'd do edited_by_user_id as the column name. The more descriptive the better.

Please sign in or create an account to participate in this conversation.