Darius
Darius

Reputation: 268

Random data from another Model relationship in Laravel

I have 2 Models(Category and Company) with relationship between them. I want to show random Companies. How to use inRandomOrder/shuffle() in subquery.

I tried this. But it shuffle Category, but not Companies. I need opposite.

$categoriesAll = \App\Category::all()->shuffle();

My view looks like this:

@foreach ($categoriesAll as $categoryAll)
  <div class="header">
    <i class="{{ $categoryAll->icon }} icon-bg-{{ $categoryAll->id }}"></i> 
    <h4>{{ $categoryAll->name }}</h4>
  </div>
<ul class="category-list" >
    <?php   $j= 0; ?>
    @foreach ( $categoryAll->companies as $singleCompany)
        <li><a href="category.html">{{ $singleCompany->name}} </a></li>
        <?php if (++$j == 4) break; ?>
    @endforeach
</ul>
<?php if (++$i == 8) break; ?>

Thank you for your help.

Upvotes: 0

Views: 790

Answers (1)

lagbox
lagbox

Reputation: 50531

@foreach ($categoryAll->companies->shuffle() as $singleCompany)

Call shuffle on the collection you want to shuffle.

Side Notes:

We have a $loop var in foreach loops in blade that has iteration count and things like that so you dont have to create increment your own counter.

If you only want a certain amount, only take that many.

@foreach ($categoriesAll->take(8) as $categoryAll)
...
   @foreach ($categoryAll->companies->shuffle()->take(4) as $singleCompany)

Upvotes: 4

Related Questions