Getting parent json data in child level loop. (Laravel Vue js)

I have API data which I get from controller using

return parent::with('children')->get();

it gives me this:


I can display it after fetching with axios like this:

    George has 2 children:
        1. Glory
        2. Susan
    Robin has 1 child:
        1. Luke

Now my goal is to display it like this:

    Name   | parent's name 
    Glory  | George
    Susan  | George
    Luke   | Robin

is there a way to achieve it in vue js or in contoller, models or anyewhere else?


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

Define the reverse relationship between Children and Parent, in which you will return the parent model with every children; and then in your controller you return all record that have a non-null parent with their parents

return Model::where("parent_id", "<>", null)->with("parent")->get();

and then in your VueJS app you will have a JSON response of all children models along with their parents.

Method 2

I got the answer from here:
Select from multiple tables with laravel fluent query builder

so, i changed this:

return parent::with('children')->get();

to this:

  return DB::table('parent')
        ->join('children', 'parent_id', '=', '')

but first i changed the name field in parent table to parent_name

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

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x