Laravel agroup data by idParent

I use laravel to make a api and now I need help to agroup records in my table companies.

I use this code to make get data:

Company::orderBy('created_at')
         ->get();

And this result this data:
id | idParent | companyName
1  | null     | Company A
2  | 1        | Company B
3  | null     | Company C
4  | 3        | Company D
5  | 1        | Company E
6  | 3        | Company F

How can I get the data agroup by idParent like this:
id | idParent | companyName
1  | null     | Company A
2  | 1        | Company B
5  | 1        | Company E
3  | null     | Company C
4  | 3        | Company D
6  | 3        | Company F

Any help will be welcome.

Thanks!!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

As the result you want, it’s not grouping by it’s sorting by,
You could use:

return Company::orderBy('idParent')

Method 2

I resolve this like below:

$companies = Company::where('idParent', null)
                ->orderBy('created_at')
                ->get();  

$newCompanies = array();

foreach ($companies as $key => $value) {
    $newCompanies[] = $value;
    foreach (Company::where('idParent', $value->id)->orderBy('created_at')->get() as $key => $value) {
        $newCompanies[] = $value;
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x