Nitish Kumar Nitish Kumar - 1 year ago 68
PHP Question

How to fetch more row from a pivot table in laravel

Hi i'm trying to build a app where there are parent element which have children and each child has its own sub child. I'm having a pivot table which consists of user_id, plan_id and child_id, Now i'm trying to fetch the child. How can I fetch all the children in an array.:

I'm trying following code:

$user = Auth::user();
$selectplan = 1;
$children = $user->relations()->wherePlanId($selectplan)->first()->pivot->child;

I'm able to get only first child, but I've more rows to be fetched:

/**** Table Column ****
1 1 1 2 NULL NULL
1 1 2 3 NULL NULL
1 1 1 4 NULL NULL
1 2 1 7 NULL NULL
1 2 1 8 NULL NULL
1 2 3 10 NULL NULL

Help me out. Thanks

Answer Source

first only returns a single model instance; the first one matching the query constraints. In order to return a collection you need to use get

$children = $user->relations()->wherePlanId($selectplan)->get()->pivot->child;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download