Jimmy Sikh Jimmy Sikh - 5 months ago 13
PHP Question

Laravel 4 weird behavior for variable in IF condition

Am I doing something wrong?

In Laravel 4 this is not working:

$things = DB::table('things')->paginate(20);

if ($things) {
$view_data = [
'have_items' => 'yes',
];
} else {
$view_data = [
'have_items' => 'no',
];
}


I have to do this:

$things = DB::table('things')->paginate(20);

if ($things === true) {
$view_data = [
'have_items' => 'yes',
];
} else {
$view_data = [
'have_items' => 'no',
];
}


and then it works.

In other frameworks it works like
if ($things)
without any problems.

Can somebody tell me if I am doing something wrong, or is it supposed to work like that?

Answer

Can you please try to check the $things variable by using count() function? Check whether there is value or not. You can check something like this

$things = DB::table('things')->paginate(20);

if (count($things)>0) {
    $view_data = [
        'have_items' => 'yes',
    ];
} else {
    $view_data = [
        'have_items' => 'no',
    ];
} 

hope this will help :) :)

Comments