Attempt to read property "email" on int - Laravel 8

Viewed 12049

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) have: id, name, email, password etc.

Work have: id, user_id, start_date etc.

3 Answers

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

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);
}

import use App\Models\Obra; in the Controller.

use App\Models\Obra;

$obras = Obra::all();
return view("obra.index", compact("obras"));
Related