D
D
Denis2018-04-15 17:58:27
PHP
Denis, 2018-04-15 17:58:27

How to get correct data type from MYSQL in Laravel?

Hello.
I work with Laravel 5.6
The MYSQL database has columns of type int
But when I get data from the database in any way, be it models or a direct query
, I always get back all the data from the database in string format and this makes the development process very difficult, since I have to translate everything manually in Integer
Can I set some PDO settings in the connection?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
H
hakkol, 2018-04-15
@hakkol

Discussed the same here. Check that you have the normal version of php and mysql installed.

I
iljaGolubev, 2018-04-17
@iljaGolubev

https://github.com/laravel/framework/blob/1eb1314d...
If I fix it to true, I get the ID as a string.
PDO::ATTR_STRINGIFY_FETCHES => true ,
PDO::ATTR_EMULATE_PREPARES => true ,
If using pure PDO try these options.

V
Victor, 2018-04-15
@v_decadence

For models https://laravel.com/docs/5.6/eloquent-mutators#att...
For regular DB queries you really need to invent something. Why does pdo driver return int as string?

T
ThunderCat, 2018-04-17
@ThunderCat

There is some solution on SO , but it looks like something non-standard, IMHO it’s easier in the db class to add a type check when returning from the select, and return already in finished form, something like:

if($row = $sql->fetch(PDO::FETCH_ASSOC) !== false){
       foreach($row as $k=>$v) {
            if(is_numeric($v)) $row[$k] = intval($v);
        }
}

This is also a crutch, but at least you don’t have to wrap everything in checks in every request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question