Support the ongoing development of Laravel.io →
posted 5 years ago

Hi, I have this inside my test model:

public function student() { return $this->belongsTo('App\User'); }

and inside my user model:

public function tests() { return $this->hasMany('App\Test'); }

so inside the table user_tests I have a record with user_id 4 and test_id 2. Ofc I have user with id 4 and a test with id 2. In the template I am doing this:

$test->student->firstname

but I get the error that student is no object and in fact is empty. What am I doing wrong?

Thanks a lot

Last updated 2 years ago.
0

I don't think a user_tests table is necessary in this instance. If I understand your domain correctly, a user has many tests and a test has 1 user. So the following schema should work:

[users table] id, name, ...

[tests table] id, user_id, title, score, ...

Then in the User model:

public function tests()
    {
        return $this->hasMany('App\Test');
    }

Then in the Test model

 public function student()
    {
        return $this->belongsTo('App\User');
    }

joedixon liked this reply

1

thanks, in the meanwhile I realized I need a many to many for this relation...

0

Sign in to participate in this thread!

Eventy

Your banner here too?

andrea giorg Joined 13 Sep 2018

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.