How To Make Clean Forms with Laravel Blade
Building forms in our application is one of those tasks that you repeat constantly. Almost every website has forms. We are basically just building forms, over and over.
Fortunately with Laravel and the html engine Blade, building forms is already a bit easier and cleaner than if you would do the same thing in plain PHP/HTML.
With time, you'll often see yourself repeat the same code/html structure of your inputs accross your projects. And as you copy paste the same code over and over, you'll gradually improve it to add some features, like icons, error handling, red border and colors based on validation, automatic label and id attribute, etc etc.
But even with all those tools you end up with big chunk of code just for an input. Look at this snippet for a simple html input:
<div class="field">
<label for="email" class="label">
@lang('fields.email')
</label>
<div class="control {{ $errors->has('email') ? 'has-icons-right' : '' }}">
<input id="email"
type="email"
class="input is-large {{ $errors->has('email') ? 'is-danger' : '' }}"
name="email"
value="{{ old('email') }}"
placeholder="Email"
required
autofocus>
@if ($errors->has('email'))
<span class="icon is-small is-right">
<i class="fas fa-exclamation-triangle"></i>
</span>
<span class="help is-danger">
{{ $errors->first('email') }}
</span>
@endif
</div>
</div>
WOW. That's a lot of code lines for an input. Imagine having ten inputs in your forms, your HTML becomes very big and long.
Blade Components help you to package repetitive html structure into a single blade file.
This is what is looks like after:
@input([
'name' => 'email',
'label' => 'Email',
'attributes' => 'required',
])@endinput
Aaaaah. Much Cleaner. Such Wow. So Few Lines.
Now the answer to the question you are all asking in your head: BUT HOW ??
Well either you can make your own Blade component, or you can simply install this Laravel Package: mydnic/laravel-form-blade-components
composer require mydnic/laravel-form-blade-components
php artisan vendor:publish --provider="Mydnic\FormBladeComponents\FormBladeComponentsServiceProvider" --tag="blade-components"
That's it!
Have fun cleaning your templates
I consider myself as an IT Business Artisan. Or Consultant CTO. I'm a self-taught Web Developper, coach and teacher. My main work is helping and guiding digital startups.
more about meBTC
18SY81ejLGFuJ9KMWQu5zPrDGuR5rDiauM
ETH
0x519e0eaa9bc83018bb306880548b79fc0794cd08
XMR
895bSneY4eoZjsr2hN2CAALkUrMExHEV5Pbg8TJb6ejnMLN7js1gLAXQySqbSbfzjWHQpQhQpvFtojbkdZQZmM9qCFz7BXU
2024 © My Dynamic Production SRL All rights Reserved.