I am writing a Laravel 7 application using Blade views. One of my MySQL tables contains the clients tools
which have an id
that follows no specific pattern (restructuring these ids is out of discussion since they come from another system the client will not change). Some of these ids have a leading zero which is supposed to be shown in all the views, like e.g. 055A.
The ids are stored with leading zeros in the database (varchar(64)), no issue there. But when a blade view shows the ids, the leading zero is gone and moreover, the link to edit
and delete
is like myapp/public/tool/5A5/edit
which leads to an error ofc.
My approach was to show the ids with <td>{{ sprintf('%04d', $tool->id) }}</td>
but not all ids have 4 chars and still the links are like myapp/public/tool/5A5/edit
, because Blade takes the whole $tool
object. Here’s the section from my view:
@foreach($tools as $tool) <tr> <td>{{ sprintf('%04d', $tool->id) }}</td> //not enough! <td>{{ $tool->title }}</td> <td style="text-align: center;">{{ $tool->tooltype->name }}</td> @can('manage-tools', AppUser::class) <td class="td-actions text-right"> <form action="{{ route('tool.destroy', $tool) }}" method="post"> @csrf <a rel="tooltip" class="btn btn-success btn-link" href="{{ route('tool.edit', $tool) }}" data-original-title="" title=""> <i class="material-icons">edit</i> <div class="ripple-container"></div> </a> @method('delete') <button type="button" value="disabled" disabled class="btn btn-danger btn-link" data-original-title="" title="delete" onclick="confirm('{{ __("Wirklich löschen?") }}') ? this.parentElement.submit() : ''"> <i class="material-icons">close</i> <div class="ripple-container"></div> </button> </form> </td> @endcan </tr> @endforeach
From my ToolController:
public function index(Tool $model) { $this->authorize('manage-tools', User::class); return view('tools.index',['tools' => $model->get()]); }
Advertisement
Answer
Laravel will do some “magic” behind the scenes to handle id fields gracefully, for example stripping leading zeros. Since in most cases model ids are incrementing, it is comes with this behavior as a default. You can disable this behavior using the following setting on the Model you do not have an incrementing id field. In your case:
class Tool extends Model { public $incrementing = false; ....