Stefano php, milano

Stateful select box in one line with Laravel and Twig

Here is a (long) one-liner to output a stateful select box with Laravel and the Twig Bridge Bundle:

{{ Form_select('user', {'':'Select user'} | merge(user.lists('id', 'name')),Request_get('user'), {class:'form-control'})|raw }}

In the code sample, user is an Eloquent model, Request_get binds automatically to the Request::get() method of Laravel's Request facade as well as Form_select binds to Form::select(), the last array pushes a form-control class to the select tag for enhanced bootstrap styling.

Notice we are merging arrays to ensure the select box presents an empty option to beg the user to choose one:

{'':'-- Industry --'} | merge(user.lists('id', 'name'))

When the user submits the form to another page containing the same code snippet, our selectbox will appear with the right value already selected.

While this one-liner is long, somewhat redundant and a bit complicated it's good for quick copy-pastes and works with plain Laravel + Twig bridge. A Blade version would of course be very similar.

Tags: laravel