I'm using Laravel Framework (8.26) and PHP 8.0.5
My database is Postgresql (12.3)
This is my schema (cities table):
Column | Type | Collation | Nullable | Default |
---|---|---|---|---|
id | bigint | not null | ||
is_active | boolean | not null | true |
My Answer:
In Laravel, when using the query builder to retrieve data from a database, boolean values are automatically cast to integers. This is because PHP does not have a native boolean type, so Laravel casts boolean values to integers (0 for false and 1 for true) to maintain consistency.
If you want to retrieve the boolean values as actual boolean values in your Laravel application, you can use the `cast` method in your model to specify the data types of specific attributes. In your case, you can add the following code to your `City` model:
php
protected $casts = [
'is_active' => 'boolean',
];
This will ensure that the `is_active` attribute is treated as a boolean value when retrieved from the database.
Alternatively, you can manually cast the attribute to a boolean value in your query by using the `DB::raw` method:
php
$isActive = DB::table('cities')
->select('id', DB::raw('(is_active::int)::boolean as is_active'))
->get();
This query will cast the `is_active` attribute to a boolean value before retrieving it from the database.
Rate this post
3 of 5 based on 3978 votesComments