Attempt to read property "email" on int - Laravel 8
Solution 1:
The problem seems to be that I had the relations wrong, I had to use hasOne
in the requester model (in the end I used hasMany
because someone can create more than one work) and in the work model use belongsTo
.
IMPORTANT note: the name of the function in the model cannot be the same as the name of a field in your table. Also in my case the column names do not follow the laravel/eloquent nomenclature so another parameter is added to belongsTo
with the field name.
Work model:
public function solicitante(){
return $this->belongsTo(User::class, "requestor_id");
}
Requestor model:
public function obra(){
return $this->hasMany(Obra::class, "requestor_id");
}
And how to obtain requester data: $obra->solicitante->email
Solution 2:
I think it's because of the name of the relation. You can try to renaming it to requestor. Laravel has some internal behavior runing on underscore. It might return only the id.
public function requestor()
{
return $this->hasOne(User::class);
}