Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alenavafer's avatar

Access data 3 tables

Hi, I have 3 tables

users (id, name, lastname)
extra (id, title)
users_extras (id, user_id, extra_id)

If I want to know how extra data from a user I write this in users model

public function extras()
    {
        return $this->belongsToMany('App\Extras', 'users_extras', 'user_id', 'id');
    }

But I have an error "Undefined property: Illuminate\Database\Eloquent\Collection::$extras"

What is wrong, I am new in Laravel.

Thanks

0 likes
7 replies
thepsion5's avatar

You're probably returning a collection of users instead of a single user. Can you post the code the performs the user query?

spodlogar's avatar

while doing manyToMany relationships you want the join table to have the columns in alphabetical order:

users (id, name, lastname)
extra (id, title)
extras_users (id, user_id, extra_id)

but if you did not do that you want your function set up like this

public function extras()
{
    return $this->belongsToMany('App\Extras', 'extras_users', 'user_id', 'extra_id'); // belongsToMany('MODEL YOU WANT TO ACCESS', 'PIVOT TABLE', 'LINK TO CURRENT MODEL', 'LINK TO OTHER MODEL');
}
alenavafer's avatar

Thanks, I keep investigating and I have this problem now

Table users-> id=1, name=John
Table extras-> id=1, title=Country -- id=2, title=Sex -- id=3, title=Phone
Table users_extras-> id=1 users_id=1 extras_id=1 -- id=2 users_id=1 extras_id=2

class UserController extends Controller
{
    public function index(Request $request)
        {
        $users = Users::find(1);

        foreach ($users->extras as $a){
            echo $a->title . '<br />';
        }
    }

But only returns Country

spodlogar's avatar

what happens if you try

public function index(Request $request)
        {
        $users = Users::find(1);

    return count($user->extras);        
    }
sid405's avatar

@alenavafer If you don't mind me asking, why have an extra table for user properties. Are your users changing Country, Sex and Phone that often? Is there a value in keeping historical data for this?

alenavafer's avatar

@spodlogar returns 1 @sid405 this is a demo app, thinks users as students and extras as extracurricular classes, so there is a table for users, other for extracurricular classes and the last for join this tables

PLB-RR's avatar

Replace

public function extras()
    {
        return $this->belongsToMany('App\Extras', 'users_extras', 'user_id', 'id');
    }

With

public function extras()
    {
        return $this->belongsToMany('App\Extras', 'users_extras', 'user_id', 'extra_id');
    }

You are joining on the id of the pivot relation instead on the extra_id. (You could remove id column from the pivot table)

Easier is to rename table to extra_user. Then use

public function extras()
    {
        return $this->belongsToMany('App\Extras');
    }

Please or to participate in this conversation.