Search code examples
laravelintegertrimvarchar

I am using "table field/column" as varchar type not integer type. But why trimming first 0(zero)?


Here, "Phone" is a field of "Employee" table and "Phone" type is string/varchar.

Steps: 1) Save one "Employee" information with phone = "01679420786"

Migration:

public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->string('phone')->primary();
        $table->string('name');
        $table->string('designation');
        $table->timestamps();
    });
}

Model:

class Employee extends Model
{
    protected $primaryKey = 'phone';
}

2) Get Employee and and then dd()

public function getEmployee()
{
    $employee = Employee::get();
    dd($employee[0]->phone);
    return view('employee.showEmployeeList')->with('employee', $employee);
}

3) Output in browser: 1679420786

Using Laravel Framework 6.0.3, PHP Version: 7.3.2


Solution

  • You are setting the primary key of the model to phone. In this case it is a string. By default, Laravel is expecting this to be an integer and so is trying to cast the value to an integer. This is removing the 0 from the start of the value.

    In order to solve this, add the following property to your model.

    protected $keyType = 'string';
    

    This tells Laravel that the primary key is not an integer and it is instead a string, so it will cast it accordingly.

    Your model should then look something like the following:

    class Employee extends Model
    {
        protected $primaryKey = 'phone';
    
        protected $keyType = 'string';
    }