inRandomOrder()->take(4) won't work

Published 7 months ago by splendidkeen

I'm currently trying to make my application more dynamic and intelligent. Therefore I wanted to parse partials of content (1) inRandomOrder()->take(x) & (2) inRandomOrder->take(x) + based on specific content (e.g. a city or street) on my home view

This is my setup for case (1)

HomeController

public function home()
    {
        $businesses = Business::inRandomOrder()->take(4); 
        return view ('home', compact('businesses'));
    }   

homeblock.blade.php


<div class="col-md-3 col-sm-6 col-xs-12">
<div>
    <a href="#"><h4>{{$business->company_name}}</h4></a>
    <a href="#"><p>{{$business->city}}, {{$business->street}}</p></a>

</div>
</div> 
 

home.blade.php

<div class="row" id="genre-display-2"> 
    @each(partials.homeblock', $businesses, 'business')   
</div>

But it won't show any businesses, am I missing something?

Thank you

Best Answer (As Selected By splendidkeen)
bobbybouwmann

What does inRandomOrder do for you? If that is a query scope (at least I expect it is) you still need to finish of the query. take(4) will only add limit 4 to the query, but not execute it.

This should work for you

$businesses = Business::inRandomOrder()->take(4)->get();
bobbybouwmann

What does inRandomOrder do for you? If that is a query scope (at least I expect it is) you still need to finish of the query. take(4) will only add limit 4 to the query, but not execute it.

This should work for you

$businesses = Business::inRandomOrder()->take(4)->get();
splendidkeen

Great this works, thank you @bobbybouwmann

How can I make it more dynamic such as e.g displaying a collection of businesses from a city x?

And would it even be possible to make the partial dynamic such as?

if(there are only (count) 2 businesses)
<div class="col-md-6">
...
</div>

@elseif(there are only (count) 3 businesses)
<div class="col-md-4">
...
</div>
@endif
bobbybouwmann

Well you can do a count on the results right

@if ($businesses->count() === 3) 
    // Do something
@elseif ($businesses->count() === 2)    
    // Do something
@endif
splendidkeen

Cool, that works fine. Thank you @bobbybouwmann

bobbybouwmann

Great :D

splendidkeen

Could I even merge content of two Models within one collection? @bobbybouwmann

Such as

$collection = (Model1::inRandomOrder()&&Model2::inRandomOrder())->take(4)->get();

return view ('home', compact('collection');

homeblock

if($collection instance === Model 1)

// show div of Model 1

else ($collection instance === Model 2)

// show div of Model 2

endif 

Please sign in or create an account to participate in this conversation.