why Laravel controller doesn't show the zero leading when search from number starts with 0

1.3k Views Asked by At

I'm using laravel and I can create a record with barcode = 069, or barcode = 006, however when I Click the search button, it shows 69 in the form, below view, controller...etc, please I need help:

HTML where i enter value to search:

<div class="container my-container">
  <div class="lead text-center font">
    <h3><strong><u> Search Form</u></h3></strong>
  </div>
  <form action="{{ route('store.show')}}" method="GET">
    {{ csrf_field() }}
    <div class="input-group">
      <input type="text" class="form-control" required name="name" placeholder="Scan Barcod">
      <span class="input-group-btn">
        <button type="submit" class="btn btn-primary" name="submit"  value="serach">
          <span class="glyphicon glyphicon-search"></span>
        </button>
      </form>
    </div>

Controller: for the same view

public function show()
{
    $saved_barcode= request('name');
    $searchbyfield = store::find($saved_barcode);

    if ($searchbyfield) {
        return view('store.show', ['store'=> $searchbyfield]);
    }

    return redirect('store/create')->with('missing', 'Item not Found');
}

HTML where show the search result

<form action= "{{ route('store.editbarcode',$store -> barcode) }}"  method="GET">
  {{ csrf_field() }}
  <div class="input-group">
    <span class="input-group-addon">
      <strong>Asset ID </strong></strong>
      <span style="color: red">*</span>
    </span>
    <input disabled  type="text" class="form-control" required id="barcode" name="barcode" value="{{ $store -> barcode }}">
    <span class="input-group-btn">
      <button type="submit" class="btn btn-primary" name="submit" >
        <span class="glyphicon glyphicon-edit"></span>
      </button>
    </form>
  </div>
2

There are 2 best solutions below

3
On

This is most probably because you are saving barcode value in integer type column.

To allow your database engine store leading zeros, you should change the column type to varchar or string as in Laravel. It will solve your problem.

3
On

Assuming the Store has barcode as a string, you could pass the search input as a string instead of int, cuase when you pass it to ->find() it gets casted as int What you can do is in your controller:

public function show()
{
         $saved_barcode= request('name');
         $searchbyfield = store::where('barcode', $saved_barcode)->first();
         if ($searchbyfield) {
            return view('store.show', ['store'=> $searchbyfield]);
         }
         return redirect('store/create')->with('missing', 'Item not Found');
}

EDIT

After reading what you said, perhaps you would wanna set this value in your Store model:

protected $primaryKey = 'barcode';
public $incrementing = false;
protected $keyType = 'string';