How To Retrieve Data With Zeros In Eloquent

- 1 answer

I am creating a student number from retrieving multiple data from database.

Like Course_ID.Year_Code.Student_no

In order to retrieve same digit numbers I fill my raw student number (which is given on creation) as 0001, 0002.

When I try to retrieve my student number by getting this number from database

I get results without zeros.

Lets say Course_ID 22 and Year_Code 16

and Student_NO 0005

I return number as 22165 which should be 22160005. this is how I get students.

$students = \App\Student::with('payment')->where('branch', $id)->get();

(I actually recieve student_no without zeros with the query below)

and this is how I write in blade

<td>{{$student->Course_ID.$student->course->year_code.$student->student_no}}  </td>

PS: I do know how to retrieve numbers with native php by using str_pad. I ask if there is a method to do it on Eloquent.



There is no straightforward way to do that that Eloquent would offer so you'd need to add some logic yourself.

One option would be to store student_no as a string in the database, otherwise zeros will be lost when it's fetched as an integer in PHP, as PHP doesn't care about your ZEROFILL and treats 0005 as 5.

Another option is to append zeros manually in PHP after fetching data from the database, e.g. by adding an accessor in your model:

public function getStudentNoAttribute() {
  return sprintf("%05d", $this->attributes['student_no']);

This way, whenever you access student_no attribute of your model it would be converted to zero-filled string automatically.