I have a Work model where one of its attributes is the requestor, I am trying to obtain the requestor´s data (I can already obtain the primary key).
In this way I call the view:
$obras = Obra::all();
return view("obra.index", compact("obras"));
The view:
@forelse ($obras as $i)
<li>{{ $i->requestor_id->email }}</li>
@empty
The relationship in the work model:
public function requestor_id() {
return $this->hasOne(User::class);
}
Tables:
Users (applicants)
- id
- name
- email
- password
Work
- id
- user_id
- start_date
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