Marco Marco - 2 months ago 8
MySQL Question

Laravel - query where last two are equal to

I need to make a query where I need to check if the last two rows have the column

answered
equal to string 'not'. That is the condition for the if loop in my controller:

$inactive = Answer::orderBy('created_at', 'desc')
->where('answered', 'not')
->where('player_id', $player->id)
->where('quiz_id', $quiz->id)
->take(2);

if ($inactive) {
// The game was finished
$opponent = $quiz->getOpponent($player);
$quiz->status = 'finished';
$quiz->save();

Event::fire(new GameEvent(
'quizFinished',
[
$opponent->user,
$player->user,
],
[]
));
}


But it is not working as I expected since the if loop is being entered even when it shouldn't be.

Answer

You have made a very small mistake

$inactive = Answer::orderBy('created_at', 'desc')
                            ->where('answered', 'not')
                            ->where('player_id', $player->id)
                            ->where('quiz_id', $quiz->id)
                            ->take(2)
                            ->get();

Notice the ->get().

Without that, the $inactive is still an eloquent object. which means that it is not null.

Refer: https://laravel.com/docs/5.1/eloquent#retrieving-multiple-models