Laravel show zeros when using zerofill in Eloquent

David Carr

Laravel Framework Tutorials PHP & MySQL

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;

 

Fathom Analytics $10 discount on your first invoice using this link

Help support the blog so that I can continue creating new content!

Sponsor

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.