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

adityar15's avatar

Laravel - Join to get result as a nested array

I am looking to construct a join query to join three tables namely table product, attribute and subattribute.

I want to have result as

{
id: 1,
name: Phone,
attribute: color,
subattribute: [red, green blue]
}


How should the join query look like?

Thanks in advance :)

0 likes
6 replies
adityar15's avatar

@mirasmustimov thanks for the answer. I tried eloquent models but still, I am getting the same results. For each sub-attribute, I am getting different collection something like this"

[{id:1,
name:Phone,
atrribute:color,
subattribute: red
},
{id:1,
name:Phone,
atrribute:color,
subattribute: green
},
{id:1,
name:Phone,
atrribute:color,
subattribute: blue
},


Not sure if I am missing something

adityar15's avatar

Hi @mirasmustimov

Currently, I am trying with a simple product and category relationship. I believe if this gets working then I could do others too.


//Categories.php

<?php

namespace App;

use App\Products;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Categories extends Model
{
    use HasFactory;
    protected $guarded = [];
    protected $table = 'tablename';

    public function products(){
        $this->hasMany(Products::class);
    }
}




// Products.php



<?php

namespace App;

use App\Categories;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Products extends Model
{
    use HasFactory;
    protected $guarded = [];
    protected $table = 'tablename';

    public function categories(){
        return $this->belongsTo(Categories::class,'fk', 'pk');
    }
}


I am getting two separate collections for the same categories. I am looking like all the products are listed under the same categories

MirasMustimuly's avatar

Hi, show the code that fetches data and also expected and actual result of that code

Please or to participate in this conversation.