Laravel Framework, PHP & MySQL, Tutorials

Laravel show zeros when using zerofill in Eloquent

When using Eloquent leading zeros are removed from integers data types. This is a problem when you want to display zero numbers in cases such as order numbers like 0034.

To achieve this in your model create an attribute filed, give the attribute a different name to the column in the database.  Note attributes are prefixed with get and end with Attribute.

Using str_pad to zero fill up to x zeros by passing the column to return an the number of digits wanted in total.

function getOrderNoAttribute() {
    return str_pad($this->id,4,'0',STR_PAD_LEFT);
}

Then when displaying the data reference the attribute

$model = Model::find(1);
$model->OrderNo;

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.