Laravel 5.4 Eloquent get x random records from collection where property is null

1.8k views Asked by At

Learning eloquent/laravel. I have a collection:

$regions = Region::with('neighbors')
    ->join('cards', 'cards.id', '=', 'regions.risk_card_id')
    ->get();

I have a value or rows:

$regionsPerUser = 8;

I am doing this to pull random records:

$regions = $regions->random($regionsPerUser);

But I need to filter this selection where $regions->user_id is not null.

Is there a way to filter the random call as part of chaining?

I tried this which does not work:

$regions = $regions->whereNotNull('user_id')->random($regionsPerUser);

And I am wondering if there is a way to neatly do this in one chained statement as opposed to going down the path of filter / map.

1

There are 1 answers

1
u_mulder On BEST ANSWER

Why not just add your conditions to a sql-query:

$regions = Region::with('neighbors')
    ->join('cards', 'cards.id', '=', 'regions.risk_card_id')
    ->whereNotNull('user_id')
    ->inRandomOrder()
    ->limit($regionsPerUser)
    ->get();

If you already have a collection then you can do something like:

$regions = $regions
    ->filter(function ($value) {
        return !is_null($value['user_id']);
    })
    ->random($regionsPerUser);