I have two models named: Subject and Group, Subject has a group_id column with a foreign key setup to point to the groups’ table.
When I call $subject->group it returns null; it should return the Group model that the Subject belongs to. I can manually get the Group by calling Group::where(‘id’, ‘=’, $subject->group_id) and that works fine. The $subject variable is also working as expected.
What I’ve tried in the Subject model:
// Not all at once obviously, it's just easier to show what I've tried like this.
public function group(): BelongsTo {
return $this->hasOne(Group::class, 'id', 'group_id');
return $this->belongsTo(Group::class, 'id', 'group_id');
return $this->belongsTo(Group::class);
}
web.php:
Route::get('/subjects/{subject}', [AppHttpControllersSubjectsController::class, 'subject'])->name('subject');
How I’m testing in my controller:
public function subject(Request $request, Subject $subject)
{
dd($subject->group);
}
dd($subject) returns a subject model object filled with expected data. Returning $subject->group() returns a group model object but no data in it.
What I’ve tried so far:
// php artisan tinker:
$s = Subject::first(); $g = Group::where('id', $s->group_id)->firstOrFail();
Returns
IlluminateDatabaseEloquentModelNotFoundException No query results for model [AppModelsGroup].
$testSub = Subject::where('id', '=', 4074)->first();
$testGroup = Group::where('id', '=', $testSub['group_id'])->first();
dd($testSub, $testGroup, $testSub->group);
Returns the subject and group model objects filled with the expected data. $testSub->group returns null.
I called
dd($student->is($testSub));
And it returns true
Something that does work is:
$subject->group()->get()
But that isn’t ideal.
Using ‘with’ either in the model as a protected member or calling the method, does not work.
2
Answers
Turns out I had another column named 'group' in the subjects table that was interfering. Changed the name of the method and it works now.
Check if the input parameter "$subject" has right data.
I use the following relationship in the subject model can get the group data.