Fix: Making base form input with @error laravel

 In Laravel, you can create a base form input with the `@error` directive to easily handle input errors and old input values. Here's how you can do it:


1. **Create a Base Input Component:**


   Laravel allows you to create Blade components to encapsulate reusable UI elements. You can create a base input component to handle form inputs.


   First, create a Blade component file, e.g., `resources/views/components/form-input.blade.php`. In this file, you can define the structure of your input element and handle errors:


   ```blade

   <div class="form-group">

       <label for="{{ $name }}">{{ $label }}</label>

       <input type="{{ $type }}" name="{{ $name }}" id="{{ $name }}" class="form-control @error($name) is-invalid @enderror" value="{{ old($name) ?? $value }}">

       @error($name)

           <span class="invalid-feedback" role="alert">

               <strong>{{ $message }}</strong>

           </span>

       @enderror

   </div>

   ```


2. **Include the Component in Your Blade View:**


   In your form views, you can include the `form-input` component with the necessary parameters. Here's an example of how to include it in a Blade view:


   ```blade

   <x-form-input

       label="Username"

       name="username"

       type="text"

       value="{{ $user->username }}"

   />

   ```


   In this example, the `x-form-input` component is included with the label, name, type, and value attributes. The component will handle displaying the input, errors, and old input values.


3. **Render the Blade Component:**


   To render the Blade component, you must make sure your application is running Laravel 7 or later (as Blade components were introduced in Laravel 7). Also, ensure that your Blade view uses the `x` directive.


   If you are using Laravel 8, you likely have Blade components enabled by default.


4. **Styling**:

   You can style the input and error messages as needed in your CSS or using any front-end framework you prefer.


This approach simplifies the process of creating form inputs and handling errors by encapsulating them in a reusable component. You can easily customize the form input's structure and behavior in the `form-input.blade.php` file, and then use it in your Blade views as needed.

Comments

Popular posts from this blog

bad character U+002D '-' in my helm template

GitLab pipeline stopped working with invalid yaml error

How do I add a printer in OpenSUSE which is being shared by a CUPS print server?