Home > database >  Refactoring Laravel isset params to eloquent when condition
Refactoring Laravel isset params to eloquent when condition

Time:04-04

I am trying to clean up my code, so i have decided to start using the when option instead of isset in my querys ... But it doesnt seem to be working and I cant see where I am going wrong.

My original code looks like so;

$params['game'] = 'fallout';

$gameQuery = Gaming::query();

$gameSelect = isset($params['game']) ? $params['game'] : null;
if ($gameSelect) {
    $gameQuery = $gameQuery->where('game' $gameSelect);
}

This has been working in the codebase now for a number of years.

I tried refactoring to the following, using the when keyword

$params['game'] = 'fallout';

$gameQuery = Gaming::query();

$gameQuery->when($params['game'], function ($query) use ($params) {
    $query->where('game', $params['game']);
});

But for some reason it just skips over there where statement.

Any help would be greatly appreciated.

CodePudding user response:

$gameQuery->when(isset($params['game']) 
, function ($query) use ($params) {
     $query->where('game', $params['game']);
 });
  • Related