skip to Main Content

I am using Laravel with database SQL Server my PHP version is 7.4 and my driver version 5.9.

I have a problem if the data is viewed from the Microsoft Management SQL Server database, numeric or decimal data types if we view data in database the result is 0.5, but when in Laravel I retrieve the query data the result is ,5 there is no 0 before decimal. is this a bug driver SQL Server?

PICTURE IN DATABASE

Picture when I retrive data from query laravel

For my query code Laravel.

 public function edit($id)
    {
        $tooling = DB::table('master_tooling')
        ->where('id',$id)->first();
        return view('setup.master_tooling.update',compact('tooling'));
    }

3

Answers


  1. PHP can convert the string".23" to a float, which will be represented correctly (echo (float) '.23'; prints 0.23). All your Laravel columns are strings, Laravel has attribute casting, that will change the columns to the correct types.

    Secondly, please use Eloquent models, that is what is considered best practice and way easier to work with than DB::table(). Create your model MasterTooling.php, you can create it with the following make command php artisan make:model MasterTooling. Here you can add the attribute casting, i only added ton_max and ton_warn to show.

    <?php
    
    namespace AppModels;
    
    use IlluminateDatabaseEloquentModel;
    
    class MasterTooling extends Model
    {
        protected $casts = [
            'ton_warn' => 'float',
            'ton_max' => 'float',
        ];
    }
    

    Your edit view code should now be updated to this.

    public function edit($id)
    {
        $tooling = MasterTooling::findOrFail($id);
    
        return view('setup.master_tooling.update',compact('tooling'));
    }
    
    Login or Signup to reply.
  2. In addition to mrhn’s Answer you should check it out about SQL Driver in PHP and PDO options for all your queries with strings and all numeric types. Because in PHP according to Microsoft docs.
    Numeric and Floats for PHP are strings, but the trick there is the use of implicit cast:

    $float = (float) $floatStringVariable

    Why? Because those values are provided by the driver as Numeric Strings

    Login or Signup to reply.
  3. I was faced to this issue. According to that, i used this option :

    • SQLSRV : "FormatDecimals"=>true
    • PDO_SQLSRV : PDO::SQLSRV_ATTR_FORMAT_DECIMALS => true

    After that, i’ve been getting "0.562" instead of ".562"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search