How To Make Clean Forms with Laravel Blade

profile picture

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">

	<div class="control {{ $errors->has('email') ? 'has-icons-right' : '' }}">
		<input id="email"
			class="input is-large {{ $errors->has('email') ? 'is-danger' : '' }}"
			value="{{ old('email') }}"

		@if ($errors->has('email'))
			<span class="icon is-small is-right">
				<i class="fas fa-exclamation-triangle"></i>
			<span class="help is-danger">
				{{ $errors->first('email') }}

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 to the rescue

Blade Components help you to package repetitive html structure into a single blade file.

This is what is looks like after:

	'name' => 'email',
	'label' => 'Email',
	'attributes' => 'required',

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


2021 My Dynamic Production SPRL All rights Reserved.