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

Edenlukaku's avatar

Relationship with array/object structure

Hello there,

I have 2 models like this:

Student model

class Student extends Model
{
    use HasFactory;

    public function department()
    {
        return $this->belongsTo(Department::class);
    }
}

Department model

class Department extends Model
{
    use HasFactory;

    public function students()
    {
        return $this->hasMany(Student::class);
    }
}

But I want to get the result of with relationship as one object like this:

{
    "id": 1,
    "first_name": "John",
    "last_name": "Doe",
    "department_id": 1,
    "department.name": "IT"
}

But I get this:

{
    "id": 1,
    "first_name": "John",
    "last_name": "Doe",
    "department_id": 1,
    "department": {
        "id": 1,
        "name": "IT"
    }
}

I know I can restructure the result but is there a way to do it in Eloquent? and what is the most efficient way to do this?

Thanks.

0 likes
4 replies
Edenlukaku's avatar

@frknasir Thank you for your time, it works perfect but I want to do it in Eloquent if that's possible?

Edenlukaku's avatar

@Sinnbeck Thank you for your time, I think Eloquent is somehow annoying with foreign keys when it comes to relationships. I had to select PK and FK so that the query works, even if I don't want them to exist at the final form of object output.

I will give this package a try thanks for the recommendation.

Please or to participate in this conversation.