James Holz
James Holz

Reputation: 47

How to create a collection (or array) listing all parents and their children to pass to a view

I am quite new to Laravel. I know how I could do this but don't know if it is the best method. I have a system of items called "Flows". Each of them belong to a particular "FlowCategory". I would like to retrieve all the "FlowCategory" items and then their associated children ("flows") using the controller and pass that to the view.

The view I want will show a list of each Flow Category and it's associated flows.

I've set up Eloquent and the two items have a relationship. I have created a foreach loop in in the controller and have created an array manually but I'm insure if its correct.

       foreach ($cats as $cat) {
           $catid = $cat->id;
           $flows[$catid] = \App\FlowCategory::find($catid)->flows;
       }

Upvotes: 0

Views: 443

Answers (1)

webmasterdro
webmasterdro

Reputation: 224

Alright, maybe you to do something like that. But just to refresh the concept:

  • Flows belongsTo a Flow Category
  • Flow Category hasMany Flows.

Your models:

FlowCategory:

public function flows()
{
    return $this->belongsTo('App\Flow', 'category_id');
}

Flow:

public function flowCategory()
{
    return $this->hasMany('App\FlowCategory');
}

That is, if you want to display in your view all Flow Categories, with their respective items, you can do like that:

FooController.php

public function bar() {
  // "with" is to avoid N+1 query problem
  $flowsCategories = FlowCategory::with('flows')->get();

  return view('yourview', compact('flowsCategories'));
}

And then, to display the items on your view, for each category you can do like that:

@foreach($flowsCategories as $flowCategory)
  @foreach($flowCategory->flows as $flow) 
     Flow: {{ $flow->name }} – Flow Category: {{ $flowCategory->name }}
  @endforeach
@endforeach

Upvotes: 1

Related Questions