I'm trying to set a boolean $bln
according to whether a record exists in a table.
This is what I've been trying:
$bln = (bool) DB::table('accounts')->where('name', $name)->pluck('id');
For some reason $bln
always seems to be set to true
. What am I doing wrong?
To achieve this you can use count()
method:
$bln = DB::table('accounts')->where('name', $name)->count() > 0;
If you'll need the object later, load it and use is_null()
to do the check:
$object = DB::table('accounts')->where('name', $name)->first();
$bln = !is_null($object);
I'm guessing that id
is a integer
and not boolean
type? Well I really hope it is! hehe.
What you do is fetching the id
of a given account
and casting it to bool
.
If you cast a value to bool
, it will be true as long as it does not evaluate to false , in a integers
case, only 0
will be evaluated to false when you cast it to bool
.
Check if the result count is larger than 0
and it should give the result you want.
Because pluck() return an array, you can check it with count $bln = (bool) count(DB::table('accounts')->where('name', $name)->pluck('id'));
Here is a Laravel Documentation: pluck()
Please try this.
$bln = DB::table('accounts')->where('name', $name)->get()->first();
if(isset($bln) && $bln != null || $bln != ''){
return $bln = 1;
}
else{
return $bln = 0;
}
The exists()
and doesntExist()
methods give a boolean straight out of the box, use them instead of count()
.
$bln = DB::table('accounts')->where('name', $name)->exists();
Laravel Docs : Determining If Records Exist
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.