DEV Community

Saurabh Mahajan
Saurabh Mahajan

Posted on • Originally published at ascsoftwares.com

Laravel Components to keep your Code Clean

In one of our recent Project, we had to create a lot of Forms using Livewire. The Forms were rather simple as can be seen from the following screenshot. The Forms were built on top of Laravel Breeze which comes up with some handy components for Form. However, even after using these Components, the View File had a lot of repeating HTML.

Preview

Our View File looked like below:

Preview

As you can see even with after using the Components for Label, Input and Error Message, there is still a lot of HTML which is just repeating with minor changes for each field. We decided to further organize the things by creating a Separate Component for Input Field Group which would consist of a div and then the Label, Text Input and the Error Field Component.

We created a folder form-group inside the resources/views/components Folder. And within that we created a file input.blade.php. We noticed that for each Input Form Group only label and the name are different. So we created them as @props in our Component. Our File looked like below:

@props(['label', 'field'])

<div class="mt-4">
    <x-label>{{$label}}</x-label>
    <x-input class="block mt-1 w-1/2" type="text" wire:model.defer="{{$field}}" />
    @error($field) <x-error-message>{{$message}}</x-error-message> @enderror
</div>
Enter fullscreen mode Exit fullscreen mode

So now in order to display the Name Field all we had to use the above component and pass the props as below

<x-form-group.input label="Name" field="product.name" />
Enter fullscreen mode Exit fullscreen mode

By creating similar Form Group Components for Select, Textarea and other fields we were able to reduce our View File as below:

Preview

This looks much more compact and easy to read with all the noise being removed. Depending upon the requirements, we can easily make the components defined under form-group to accept attributes and make more dynamic.

Hope you have enjoyed this Article. Let us know in comments, how you use Components to keep your View File Clean. For similar articles, you can follow me on Twitter

Top comments (0)