Hi @zakaria_tbey ,
Thanks for posting. Could you simplify it by adding a university_id to your students table?
It would simplify your query and I feel you would use this relation in many areas of your app.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello Guys,
I've been struggling with this problem for the last 48 hours
I would like to add a BelongsTo field to display Universities Drop-down in a Student Resource
Here's my models : Student -> Section -> Course -> Departement -> University
class Student extends Model
{
public function section()
{
return $this->belongsTo('App\Section');
}
}
class Section extends Model
{
public function courses()
{
return $this->belongsTo('App\Course');
}
}
class Course extends Model
{
public function departement()
{
return $this->belongsTo('App\Departement');
}
}
class Departement extends Model
{
public function university()
{
return $this->belongsTo('App\University');
}
}
I was thinking about something like this :
class Student extends Model
{
public function university()
{
return $this->section->courses->departement->university;
}
}
But it doesn't really work
Any solution to properly solve this issue ?
staudenmeir/belongs-to-through package may works but not in my case because i have custom local keys and this package doesn't support custom local keys
Hey @richardbishopme ,
It's note a course or courses problem because this is just an example and returning $this->section->course->department->university doesn't return a relationship object therefore it doesn't serve the cause in Nova
But I've found a work around for this using Eloquent Mutators to trick the Student model that i have an university_id attribute in my student table
Here's my work around for anyone who face the same issue
I'm only using Traits to make the code clean & reusable
<?php
namespace App\Traits;
trait BelongsToUniversity
{
public function initializeAppendAttributeTrait()
{
$this->append('university_id');
}
public function university()
{
return $this->belongsTo('App\University');
}
public function getUniversityIdAttribute()
{
if(empty($this->section)
|| empty($this->section->course)
|| empty($this->section->course->department)
|| empty($this->section->course->department->university)
){
return null;
}
$item = $this->section->course->department->university->toArray();
return isset($item['id']) ? $item['id'] : null;
}
public function setUniversityIdAttribute($attr)
{
$this->university_id = $attr;
}
}
<?php
class Student extends Model
{
use \App\Traits\BelongsToUniversity;
....
Now you can get a belongsTo university relationship by simply calling (new Student())->university()
Please or to participate in this conversation.