Garet
6 months ago
172
9
Tips

Defining form input fields from controller

Posted 6 months ago by Garet

One thing that bugged me a little with Laravel is how we specify form input fields directly in the view.

I come from a CodeIgniter background where generally you define your form input fields from the controller.

What I have done in Laravel is written a little helper function called formInput() which takes an array, defined in the controller, to generate form input fields in the view.

Here's an example:

class CustomerController extends Controller
{
    // Show the create a new customer form
    public function create()
    {
        // Define the fields for our view
         $fields = [
            'company' => [
                'type'        => 'text',
                'name'        => 'company',
                'placeholder' => 'Enter company name',
                'required'    => 'required',
                'maxlength'   => 35,
                'value'       => old('company'),
                'class'       => 'form-input',
            ],
        ];
        // Return the view
        return view('customer/edit', [
            'fields'   => $fields,
        ]);
    }
}

And then in my view I can do this:

<!-- Display the company form input -->
{!! formInput($fields['company']) !!}

I have omited my formInput() helper function for brevity, but essentially this looks at all the attributes passed to it and generates an input tag with those attributes.

Is there any issue with this? A good reason not to do it? It just feels like defining the form input, along with its max length, whether it's required or not, is really a job for the controller and not for the view.

What do you think?

Please sign in or create an account to participate in this conversation.