m33bo
m33bo

Reputation: 1354

Merging two models into one database call - laravel

I have 2 models, that I am calling via all:

$blocks = Block::all();
$cats = BlockCategory::all();

A block has a category associated with it and I want to associate the data so that I can display all categories that have certain blocks. I hope I am explaining this correctly.

so I can call:

@foreach($cats as $cats)
    {{$cats->title}}
    @foreach($cats->blocks as $blocks)
         {{$block->title}}
    @endforeach
@endforeach

any ideas how to merge the data? I am basically building a menu if that helps.

Upvotes: 1

Views: 495

Answers (2)

Sagar Gautam
Sagar Gautam

Reputation: 9369

You need to define relationship between blocks and block category. Make sure that your db table has a foreign key relationship.

Add following code to your block category model

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

Make sure your block model is inside app/ directory.

Now, just retrieve categories in your controller,

$categories = BlockCategory::all();

Then you can display the data like this:

@foreach($categories as $category)
    {{$category->title}}
    @foreach($category->blocks as $block)
        {{$block->title}}
    @endforeach
@endforeach

Upvotes: 2

Dax
Dax

Reputation: 827

You have a few options on how to approach this.

Define your relation like this:

Model

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

Controller

Using with()

$categories = Blockcategory::with('blocks')->get();

Once you have defined the relationship you can call the blocks() method from your model to retrieve the blocks

Examples

$categories = Blockcategory::find(1)->blocks()->get();

// another way

$blocks = Blockcategory::blocks()->get();

Sagar's answer is fine, but it is always better to get your categories and their relationships in the same query. By just calling Blockcategory::all() you can get the relation in your blade file, but laravel has to do an additional query for each block in your for each loop. This can give performance issues when having 1000s of records.

Laravel relationships

Upvotes: 0

Related Questions