Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork106
A set of Blade components to rapidly build forms with Tailwind CSS (v1.0 and v2.0) and Bootstrap 4/5. Supports validation, model binding, default values, translations, Laravel Livewire, includes default vendor styling and fully customizable!
License
protonemedia/laravel-form-components
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
⚠️ This package is deprecated. It doesn't support Livewire 3 and Tailwind 3 and won't be maintained anymore.
A set of Blade components to rapidly build forms withTailwind CSS v1,Tailwind CSS v2,Bootstrap 4 andBootstrap 5. Supports validation, model binding, default values, translations, includes default vendor styling and fully customizable!
❤️ We proudly support the community by developing Laravel packages and giving them away for free. If this package saves you time or if you're relying on it professionally, please considersponsoring the maintenance and development. Keeping track of issues and pull requests takes time, but we're happy to help!
Did you hear about Laravel Splade? 🤩
It's themagic of Inertia.js with thesimplicity of Blade.Splade provides a super easy way to build Single Page Applications using Blade templates. Besides that magic SPA-feeling, it comes with more than ten components to sparkle your app and make it interactive, all without ever leaving Blade.
📺 Want to see this package in action? Join the live stream on November 19 at 14:00 CET:https://youtu.be/7eNZS4U7xyM
- Components for input, textarea, select, multi-select, checkbox and radio elements.
- Support for Tailwind v1 withTailwind CSS Custom Forms.
- Support for Tailwind v2 withTailwind Forms.
- Support forBootstrap 4 Forms.
- Support forBootstrap 5 Forms.
- Component logic independent from Blade views, the Tailwind and Bootstrap views use the same logic.
- Bind a target to a form (or a set of elements) to provide default values (model binding).
- Support forLaravel Livewire v2.
- Support for Spatie'slaravel-translatable.
- Re-populate forms withold input.
- Validation errors.
- Form method spoofing.
- Components classes and Blade views fully customizable.
- Support for prefixing the components.
- PHP 8.0 or higher
- Laravel 9.0
You can install the package via composer:
composer require protonemedia/laravel-form-components
If you're using Tailwind, make sure the right plugin (v1 orv2) is installed and configured.
<x-form>@bind($user) <x-form-inputname="last_name"label="Last Name" /> <x-form-selectname="country_code":options="$options" /> <x-form-selectname="interests[]":options="$multiOptions"label="Select your interests"multiple /><!-- \Spatie\Translatable\HasTranslations--> <x-form-textareaname="biography"language="nl"placeholder="Dutch Biography" /> <x-form-textareaname="biography"language="en"placeholder="English Biography" /><!-- Inline radio inputs--> <x-form-groupname="newsletter_frequency"label="Newsletter frequency"inline> <x-form-radioname="newsletter_frequency"value="daily"label="Daily" /> <x-form-radioname="newsletter_frequency"value="weekly"label="Weekly" /> </x-form-group> <x-form-group> <x-form-checkboxname="subscribe_to_newsletter"label="Subscribe to newsletter" /> <x-form-checkboxname="agree_terms"label="Agree with terms" /> </x-form-group> <x-form-submit />@endbind</x-form>
At first sight, generating HTML forms with PHP looks great. PHP's power can make it less repetitive, and it's nice to resolve input values and validation states right from your PHP code. Still, it gets harder to keep your PHP code clean and neat whenever your forms get more complex. Often you end up with lots of custom code, writing extensions, and overriding defaults, just for the sake of adding some small thing to your form.
After years of trying all sorts of form builders, it feels like just writing most of the form in HTML is the most versatile solution. You can add helper texts, icons, tooltips, popovers, custom sections, and JavaScript integrations however and wherever you like. The power ofLaravel Blade Components allows us to add all kinds of features without bringing the whole form-building process into PHP.
Let's take a look at thisx-form example. Theaction attribute is optional, but you can pass a hard-coded, primitive value to the component using a simple HTML attribute. Likewise, PHP expressions and variables can be passed to attributes using the: prefix. Do you need Alpine.js or VueJS directives? No problem!
<x-formaction="/api/user"><!-- ...--></x-form>
<x-form:action="route('api.user.store')"v-on:submit="checkForm"><!-- ...--></x-form>
You can switch frameworks by updating theframework setting in theform-components.php configuration file. Check out thecustomization section on publishing the configuration and view files. If you're using theLivewire Stack with Laravel Jetstream, you probably want to set theframework configuration key totailwind-forms-simple.
return ['framework' =>'bootstrap-4',];
No further configuration is needed unless you want tocustomize the Blade views and components.
The minimum requirement for aninput ortextarea is thename attribute.
<x-form-inputname="company_name" />
Optionally you can add alabel attribute, which can be computed as well.
<x-form-inputname="company_name"label="Company name" /><x-form-inputname="company_name":label="trans('forms.company_name')" />
You can also choose to use aplaceholder instead of a label, and of course you can change thetype of the element.
<x-form-inputtype="email"name="current_email"placeholder="Current email address" />
By default, every element shows validation errors, but you can hide them if you want.
<x-form-textareaname="description":show-errors="false" />
You can use thedefault attribute to specify the default value of the element.
<x-form-textareaname="motivation"default="I want to use this package because..." />
Instead of setting a default value, you can also pass in a target, like an Eloquent model. Now the component will get the value from the target by thename.
<x-form-textareaname="description":bind="$video" />
In the example above, where$video is an Eloquent model, the default value will be$video->description.
If you use Eloquent'sDate Casting feature, you can use the date attributes in your forms by setting theuse_eloquent_date_casting configuration key totrue. For compatibility reasons, this is disabled by default.
return ['use_eloquent_date_casting' =>true,];
You can either use thedates property or thecasts property in your Eloquent model to specify date attributes:
class ActivityModelextends Model{public$dates = ['finished_at'];public$casts = ['started_at' =>'date','failed_at' =>'datetime','completed_at' =>'date:d-m-Y','skipped_at' =>'datetime:Y-m-d H:i', ];}
<x-form-inputname="completed_at":bind="$activity" />
In the example above, the default value will be formatted like31-10-2021.
You can also bind a target by using the@bind directive. This will bind the target to all elements until the@endbind directive.
<x-form>@bind($video) <x-form-inputname="title"label="Title" /> <x-form-textareaname="description"label="Description" />@endbind</x-form>
You can even mix targets!
<x-form>@bind($user) <x-form-inputname="full_name"label="Full name" />@bind($userProfile) <x-form-textareaname="biography"label="Biography" />@endbind <x-form-inputname="email"label="Email address" />@endbind</x-form>
You can override the@bind directive by passing a target directly to the element using the:bind attribute. If you want to remove a binding for a specific element, pass infalse.
<x-form>@bind($video) <x-form-inputname="title"label="Title" /> <x-form-input:bind="$videoDetails"name="subtitle"label="Subtitle" /> <x-form-textarea:bind="false"name="description"label="Description" />@endbind</x-form>
You can use the@wire and@endwire directives to bind a form to a Livewire component. Let's take a look at theContactForm example from the official Livewire documentation.
useLivewire\Component;class ContactFormextends Component{public$name;public$email;publicfunctionsubmit() {$this->validate(['name' =>'required|min:6','email' =>'required|email', ]); Contact::create(['name' =>$this->name,'email' =>$this->email, ]); }publicfunctionrender() {returnview('livewire.contact-form'); }}
Normally you would use awire:model attribute to bind a component property with a form element. By using the@wire directive, this package will automatically add thewire:model attribute.
<x-formwire:submit.prevent="submit">@wire <x-form-inputname="name" /> <x-form-inputname="email" />@endwire <x-form-submit>Save Contact</x-form-submit></x-form>
Additionally, you can pass an optional modifier to the@wire directive. This feature was added in v2.4.0. If you're upgrading from a previous versionand you published the Blade views, you should republish themor update them manually.
<x-formwire:submit.prevent="submit">@wire('debounce.500ms') <x-form-inputname="email" />@endwire</x-form>
It's also possible to use thewire:model attribute by default. You may set thedefault_wire configuration setting totrue or a modifier likedebounce.500ms. This way, you don't need the@wire and@endwire directives in your views. You may still override the default setting by using the@wire directive, or by manually adding thewire:model attribute to a form element.
Besides thename attribute, theselect element has a requiredoptions attribute, which should be a simplekey-value array.
$countries = ['be' =>'Belgium','nl' =>'The Netherlands',];
<x-form-selectname="country_code":options="$countries" />
You can provide aslot to theselect element as well:
<x-form-selectname="country_code"> <optionvalue="be">Belgium</option> <optionvalue="nl">The Netherlands</option></x-form-select>
If you want a select element where multiple options can be selected, add themultiple attribute to the element. If you specify a default, make sure it is an array. This applies to bound targets as well.
<x-form-selectname="country_code[]":options="$countries"multiple:default="['be', 'nl']" />
You may add aplaceholder attribute to the select element. This will prepend a disabled option.
This feature was added in v3.2.0. If you're upgrading from a previous versionand you published the Blade views, you should republish themor update them manually.
<x-form-selectname="country_code"placeholder="Choose..." />
Rendered HTML:
<select><optionvalue=""disabled>Choose...</option><!-- other options... --></select>
This package has built-in support forBelongsToMany,MorphMany, andMorphToMany relationships. To utilize this feature, you must add both themultiple andmany-relation attribute to the select element.
In the example below, you can attach one or more tags to the bound video. By using themany-relation attribute, it will correctly retrieve the selected options (attached tags) from the database.
<x-form>@bind($video) <x-form-selectname="tags[]":options="$tags"multiplemany-relation />@endbind</x-form>
Checkboxes have a default value of1, but you can customize it as well.
<x-form-checkboxname="subscribe_to_newsletter"label="Subscribe to newsletter" />
If you have a fieldset of multiple checkboxes, you can group them together with theform-group component. This component has an optionallabel attribute and you can set thename as well. This is a great way to handle the validation of arrays. If you disable the errors on the individual checkboxes, it will one show the validation errors once. Theform-group component has ashow-errors attribute that defaults totrue.
<x-form-groupname="interests"label="Pick one or more interests"> <x-form-checkboxname="interests[]":show-errors="false"value="laravel"label="Laravel" /> <x-form-checkboxname="interests[]":show-errors="false"value="tailwindcss"label="Tailwind CSS" /></x-form-group>
Radio elements behave exactly the same as checkboxes, except theshow-errors attribute defaults tofalse as you almost always want to wrap multiple radio elements in aform-group.
You can group checkbox and radio elements on the same horizontal row by adding aninline attribute to theform-group element.
<x-form-groupname="notification_channel"label="How do you want to receive your notifications?"inline> <x-form-radioname="notification_channel"value="mail"label="Mail" /> <x-form-radioname="notification_channel"value="slack"label="Slack" /></x-form-group>
When you're not using target binding, you can use thedefault attribute to mark a radio element as checked:
<x-form-groupname="notification_channel"label="How do you want to receive your notifications?"> <x-form-radioname="notification_channel"value="mail"label="Mail"default /> <x-form-radioname="notification_channel"value="slack"label="Slack" /></x-form-group>
When a validation errors occurs and Laravel redirects you back, the form will be re-populated with the old input data. This old data will override any binding or default value.
This package supportsspatie/laravel-translatable out of the box. You can add alanguage attribute to your element.
<x-form-inputname="title"language="en":bind="$book" />
This will result in the following HTML:
<inputname="title[en]"value="Laravel: Up & Running"/>
To get the validation errors from the session, the name of the input will be mapped to adot notation liketitle.en. This is how old input data is handled as well.
Publish the configuration file and Blade views with the following command:
php artisan vendor:publish --provider="ProtoneMedia\LaravelFormComponents\Support\ServiceProvider"You can find the Blade views in theresources/views/vendor/form-components folder. Optionally, in theform-components.php configuration file, you can change the location of the Blade viewper component.
You can bind your own component classes to any of the elements. In theform-components.php configuration file, you can change the classper component. As the logic for the components is quite complex, it is strongly recommended to duplicate the default component as a starting point and start editing. You'll find the default component classes in thevendor/protonemedia/laravel-form-components/src/Components folder.
You can define a prefix in theform-components.php configuration file.
return ['prefix' =>'tailwind',];
Now all components can be referenced like so:
<x-tailwind-form> <x-tailwind-form-inputname="company_name" /></x-tailwind-form>
By the default, the errors messages are positioned under the element. To show these messages, we created aFormErrors component. You can manually use this component as well. The element takes an optionalbag attribute to specify theErrorBag, which defaults todefault.
<x-form> <x-form-inputname="company_name":show-errors="false" /><!-- other elements--> <x-form-errorsname="company_name" /> <x-form-errorsname="company_name"bag="register" /></x-form>
The label defaults toSubmit, but you can use the slot to provide your own content.
<x-form-submit> <spanclass="text-green-500">Send</span></x-form-submit>
You can switch toBootstrap 4 orBootstrap 5 by updating theframework setting in theform-components.php configuration file.
return ['framework' =>'bootstrap-5',];
There is a little of styling added to theform.blade.php view to add support for inline form groups. If you want to change it or remove it,publish the assets and update the view file.
Bootstrap 5 changes a lot regarding forms. If you migrate from 4 to 5, make sure to read the migration logs aboutforms.
In addition to the Tailwind features, with Bootstrap 4, there is also support forinput groups. Use theprepend andappend slots to provide the contents.
<x-form-inputname="username"label="Username">@slot('prepend') <span>@</span>@endslot</x-form-input><x-form-inputname="subdomain"label="Subdomain">@slot('append') <span>.protone.media</span>@endslot</x-form-input>
With Bootstrap 5, theinput groups have been simplified. You can add as many items as you would like in any order you would like. Use theform-input-group-text component to add text orcheckboxes.
<x-form-input-grouplabel="Profile" > <x-form-inputname="name"placeholder="Name"id="name" /> <x-form-input-group-text>@</x-form-input-group-text> <x-form-inputname="nickname"placeholder="Nickname"id="nickname" /> <x-form-submit /></x-form-input-group>
As of Bootstrap 5, you can addfloating labels by adding thefloating attribute to inputs, selects (excludingmultiple), and textareas.
<x-form-inputlabel="Floating Label"name="float_me"id="float_me"floating />
You can addblock-level help text to any element by using thehelp slot.
<x-form-inputname="username"label="Username">@slot('help') <smallclass="form-text text-muted"> Your username must be 8-20 characters long. </small>@endslot</x-form-input>
composertestPlease seeCHANGELOG for more information about what has changed recently.
Please seeCONTRIBUTING for details.
Laravel Analytics Event Tracking: Laravel package to easily send events to Google Analytics.Laravel Blade On Demand: Laravel package to compile Blade templates in memory.Laravel Cross Eloquent Search: Laravel package to search through multiple Eloquent models.Laravel Eloquent Scope as Select: Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.Laravel Eloquent Where Not: This Laravel package allows you to flip/invert an Eloquent scope, or really any query constraint.Laravel FFMpeg: This package provides an integration with FFmpeg for Laravel. The storage of the files is handled by Laravel's Filesystem.Laravel Paddle: Paddle.com API integration for Laravel with support for webhooks/events.Laravel Verify New Email: This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.Laravel WebDAV: WebDAV driver for Laravel's Filesystem.
If you discover any security related issues, please emailpascal@protone.media instead of using the issue tracker.
The MIT License (MIT). Please seeLicense File for more information.
This package isTreeware. If you use it in production, then we ask that youbuy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.
About
A set of Blade components to rapidly build forms with Tailwind CSS (v1.0 and v2.0) and Bootstrap 4/5. Supports validation, model binding, default values, translations, Laravel Livewire, includes default vendor styling and fully customizable!
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
