PHPackages                             spaanproductions/laravel-form - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. spaanproductions/laravel-form

ActiveLibrary[Templating &amp; Views](/categories/templating)

spaanproductions/laravel-form
=============================

HTML and Form Builders for the Laravel Framework

7.1.0(3mo ago)05.0k↓45.2%MITPHPPHP ^8.0CI passing

Since Aug 31Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/spaanproductions/laravel-form)[ Packagist](https://packagist.org/packages/spaanproductions/laravel-form)[ Docs](https://spaanproductions.nl)[ RSS](/packages/spaanproductions-laravel-form/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (10)Versions (20)Used By (0)

Laravel Form
============

[](#laravel-form)

A powerful HTML and Form Builder package for the Laravel Framework. This package provides an elegant and fluent interface for creating forms and HTML elements in your Laravel applications.

Features
--------

[](#features)

- **Form Builder**: Create forms with model binding, CSRF protection, and method spoofing
- **HTML Builder**: Generate HTML elements, links, and assets with ease
- **Eloquent Integration**: Seamless integration with Eloquent models using the `FormAccessible` trait
- **Blade Directives**: Use form and HTML helpers directly in your Blade templates
- **Component System**: Create custom form components for reusable form elements
- **Helper Functions**: Convenient helper functions for common operations
- **Type Safety**: Full support for PHP 8.0+ features and type hints

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Basic Usage](#basic-usage)
    - [Form Builder](#form-builder)
    - [HTML Builder](#html-builder)
    - [Helper Functions](#helper-functions)
    - [Blade Directives](#blade-directives)
- [Eloquent Integration](#eloquent-integration)
    - [Using FormAccessible Trait](#using-formaccessible-trait)
    - [Model Binding](#model-binding)
    - [Form Value Resolution](#form-value-resolution)
- [Custom Components](#custom-components)
- [Advanced Features](#advanced-features)
    - [Security Features](#security-features)
    - [Request Consideration](#request-consideration)
    - [Old Input Handling](#old-input-handling)
    - [Method Spoofing](#method-spoofing)
    - [File Uploads](#file-uploads)
- [API Reference](#api-reference)
    - [Form Builder Methods](#form-builder-methods)
    - [HTML Builder Methods](#html-builder-methods)
- [Troubleshooting &amp; FAQ](#troubleshooting--faq)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)
- [Support](#support)

Requirements
------------

[](#requirements)

- PHP 8.0 or higher
- Laravel 9.0, 10.0, 11.0, or 12.0

Installation
------------

[](#installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require spaanproductions/laravel-form
```

### 2. Service Provider Registration

[](#2-service-provider-registration)

The package will automatically register itself with Laravel using auto-discovery. If you're using Laravel 5.4 or earlier, you'll need to manually register the service provider in your `config/app.php`:

```
'providers' => [
    // ...
    SpaanProductions\LaravelForm\HtmlServiceProvider::class,
],

'aliases' => [
    // ...
    'Form' => SpaanProductions\LaravelForm\FormFacade::class,
    'Html' => SpaanProductions\LaravelForm\HtmlFacade::class,
],
```

### 3. Publish Configuration (Optional)

[](#3-publish-configuration-optional)

The package doesn't require a configuration file by default, but you can publish one if you need to customize settings:

```
php artisan vendor:publish --provider="SpaanProductions\LaravelForm\HtmlServiceProvider"
```

Basic Usage
-----------

[](#basic-usage)

### Form Builder

[](#form-builder)

#### Creating Forms

[](#creating-forms)

```
// Basic form
{{ Form::open(['url' => 'users']) }}
    {{ Form::text('name') }}
    {{ Form::email('email') }}
    {{ Form::submit('Create User') }}
{{ Form::close() }}

// Form with model binding
{{ Form::model($user, ['route' => ['users.update', $user->id], 'method' => 'PUT']) }}
    {{ Form::text('name') }}
    {{ Form::email('email') }}
    {{ Form::submit('Update User') }}
{{ Form::close() }}

// Form with file upload
{{ Form::open(['route' => 'users.store', 'files' => true]) }}
    {{ Form::file('avatar') }}
    {{ Form::submit('Upload') }}
{{ Form::close() }}
```

#### Form Input Types

[](#form-input-types)

All form inputs automatically generate appropriate `id` attributes from field names for accessibility:

```
// Text inputs
{{ Form::text('name', null, ['class' => 'form-control']) }}
// Generates:

{{ Form::email('email', null, ['placeholder' => 'Enter email']) }}
{{ Form::password('password', ['class' => 'form-control']) }}
{{ Form::number('age', null, ['min' => 18, 'max' => 100]) }}
{{ Form::tel('phone', null, ['pattern' => '[0-9]{10}']) }}
{{ Form::url('website', null, ['placeholder' => 'https://example.com']) }}

// Array notation is converted to valid IDs
{{ Form::text('user[name]') }}
// Generates id="user_name"

// You can override the auto-generated ID
{{ Form::text('name', null, ['id' => 'custom-id']) }}

// Date and time inputs (all accept DateTime/DateTimeImmutable objects)
{{ Form::date('birth_date') }}
{{ Form::time('meeting_time') }}
{{ Form::datetime('event_datetime') }}
{{ Form::datetimeLocal('local_datetime') }}
{{ Form::month('month') }}
{{ Form::week('week') }}

// Passing DateTime objects (automatically formatted)
{{ Form::date('event_date', new \DateTime('2024-12-25')) }}
{{ Form::date('event_date', now()) }}  // Laravel helper
{{ Form::datetime('created_at', $model->created_at) }}  // Carbon instance

// Other input types
{{ Form::search('query', null, ['placeholder' => 'Search...']) }}
{{ Form::range('volume', 50, ['min' => 0, 'max' => 100]) }}
{{ Form::color('theme_color', '#ff0000') }}
{{ Form::file('document', ['accept' => '.pdf,.doc']) }}

// Hidden inputs
{{ Form::hidden('user_id', $user->id) }}
{{ Form::token() }} {{-- CSRF token --}}
```

#### Datalist

[](#datalist)

HTML5 datalist elements provide autocomplete suggestions for input fields:

```
{{-- Create the datalist --}}
{{ Form::datalist('browsers', ['Chrome', 'Firefox', 'Safari', 'Edge', 'Opera']) }}

{{-- Link an input to the datalist using the list attribute --}}
{{ Form::text('browser', null, ['list' => 'browsers', 'placeholder' => 'Choose a browser']) }}

{{-- Datalist with associative array --}}
{{ Form::datalist('countries', ['us' => 'United States', 'ca' => 'Canada', 'uk' => 'United Kingdom']) }}
{{ Form::text('country', null, ['list' => 'countries']) }}
```

#### Textarea

[](#textarea)

```
{{ Form::textarea('description', null, ['rows' => 5, 'cols' => 50]) }}
```

#### Select Dropdowns

[](#select-dropdowns)

```
// Basic select
{{ Form::select('country', ['us' => 'United States', 'ca' => 'Canada', 'uk' => 'United Kingdom']) }}

// Select with default value
{{ Form::select('country', $countries, 'us') }}

// Select with placeholder
{{ Form::select('country', ['' => 'Select Country'] + $countries, null, ['class' => 'form-control']) }}

// Select with option groups
{{ Form::select('category', [
    'Electronics' => ['laptop' => 'Laptop', 'phone' => 'Phone'],
    'Clothing' => ['shirt' => 'Shirt', 'pants' => 'Pants']
]) }}

// Advanced: Per-option attributes (e.g., disable specific options)
{{ Form::select('product', $products, null,
    ['class' => 'form-control'],
    ['product_1' => ['disabled' => true], 'product_3' => ['data-price' => '29.99']]
) }}

// Select range
{{ Form::selectRange('year', 2020, 2030, 2024) }}

// Select year
{{ Form::selectYear('birth_year', 1950, date('Y'), 1990) }}

// Select month (format parameter uses IntlDateFormatter patterns)
{{ Form::selectMonth('birth_month', null, ['class' => 'form-control'], 'MMMM') }}  // January, February, etc.
{{ Form::selectMonth('birth_month', null, [], 'MMM') }}  // Jan, Feb, etc.
{{ Form::selectMonth('birth_month', null, [], 'MM') }}  // 01, 02, etc.
```

#### Checkboxes and Radio Buttons

[](#checkboxes-and-radio-buttons)

```
// Checkbox
{{ Form::checkbox('terms', 1, false, ['id' => 'terms']) }}
{{ Form::label('terms', 'I agree to the terms') }}

// Radio buttons
{{ Form::radio('gender', 'male', false, ['id' => 'male']) }}
{{ Form::label('male', 'Male') }}

{{ Form::radio('gender', 'female', false, ['id' => 'female']) }}
{{ Form::label('female', 'Female') }}

// Multiple checkboxes
@foreach($interests as $interest)
    {{ Form::checkbox('interests[]', $interest->id, in_array($interest->id, $user->interests->pluck('id')->toArray())) }}
    {{ Form::label('interests', $interest->name) }}
@endforeach
```

#### Buttons

[](#buttons)

```
{{ Form::submit('Save', ['class' => 'btn btn-primary']) }}
{{ Form::button('Click Me', ['class' => 'btn btn-secondary']) }}
{{ Form::reset('Reset', ['class' => 'btn btn-warning']) }}
{{ Form::image('button.png', 'Submit', ['class' => 'btn-image']) }}
```

### HTML Builder

[](#html-builder)

#### Links

[](#links)

```
// Basic link
{{ Html::link('users', 'View Users') }}

// Link with attributes
{{ Html::link('users', 'View Users', ['class' => 'btn btn-primary']) }}

// Secure link
{{ Html::secureLink('admin/dashboard', 'Admin Dashboard') }}

// Link to asset
{{ Html::linkAsset('css/app.css', 'Stylesheet') }}

// Link to route
{{ Html::linkRoute('users.show', 'View Profile', ['user' => $user->id]) }}

// Link to action
{{ Html::linkAction('UserController@show', 'View Profile', ['user' => $user->id]) }}

// Email link (automatically obfuscated to prevent spam bots)
{{ Html::mailto('info@example.com', 'Contact Us') }}

// Secure asset link
{{ Html::linkSecureAsset('documents/report.pdf', 'Download Report') }}
```

#### Assets

[](#assets)

```
// Script tags
{{ Html::script('js/app.js') }}
{{ Html::script('js/app.js', ['defer' => true]) }}

// Style tags
{{ Html::style('css/app.css') }}
{{ Html::style('css/app.css', ['media' => 'print']) }}

// Images
{{ Html::image('images/logo.png', 'Company Logo') }}
{{ Html::image('images/logo.png', 'Company Logo', ['class' => 'logo']) }}

// Favicon
{{ Html::favicon('favicon.ico') }}
```

#### Lists

[](#lists)

```
// Ordered list
{{ Html::ol(['Item 1', 'Item 2', 'Item 3']) }}

// Unordered list
{{ Html::ul(['Apple', 'Banana', 'Orange']) }}

// Definition list
{{ Html::dl(['Name' => 'John Doe', 'Email' => 'john@example.com']) }}
```

#### Meta Tags

[](#meta-tags)

```
{{ Html::meta('description', 'This is my website description') }}
{{ Html::meta('keywords', 'laravel, php, web development') }}
{{ Html::meta('viewport', 'width=device-width, initial-scale=1') }}
```

#### Generic HTML Tags

[](#generic-html-tags)

```
{{ Html::tag('div', 'Content here', ['class' => 'container']) }}
{{ Html::tag('span', 'Inline text', ['style' => 'color: red;']) }}
```

#### Utility Methods

[](#utility-methods)

```
// HTML entity encoding/decoding
{{ Html::entities('alert("XSS")') }}  // Converts to entities
{{ Html::decode('&lt;p&gt;Hello&lt;/p&gt;') }}  // Converts back to HTML

// Email obfuscation (anti-spam)
{{ Html::email('contact@example.com') }}  // Returns obfuscated email string
{{ Html::obfuscate('Sensitive text') }}  // Obfuscates any text

// Non-breaking spaces
{{ Html::nbsp(3) }}  // Generates &nbsp;&nbsp;&nbsp;
```

### Helper Functions

[](#helper-functions)

The package provides global helper functions for convenience. These are automatically loaded and available throughout your application.

#### Available Helpers

[](#available-helpers)

```
// Get the FormBuilder instance
$form = form();
// Returns: SpaanProductions\LaravelForm\FormBuilder

// Use it programmatically
$emailInput = form()->email('contact', 'user@example.com', ['class' => 'form-control']);

// Link helpers (all return HtmlString objects)
link_to('users', 'View Users', ['class' => 'btn']);
link_to_asset('css/app.css', 'Stylesheet');
link_to_route('users.show', 'View Profile', ['user' => 1]);
link_to_action([UserController::class, 'show'], 'View Profile', ['user' => 1]);
```

#### Helper Function Signatures

[](#helper-function-signatures)

```
/**
 * Generate a HTML link
 * @param string $url
 * @param string $title
 * @param array $attributes
 * @param bool $secure
 * @param bool $escape
 * @return \Illuminate\Support\HtmlString
 */
function link_to($url, $title = null, $attributes = [], $secure = null, $escape = true)

/**
 * Generate a HTML link to an asset
 * @param string $url
 * @param string $title
 * @param array $attributes
 * @param bool $secure
 * @param bool $escape
 * @return \Illuminate\Support\HtmlString
 */
function link_to_asset($url, $title = null, $attributes = [], $secure = null, $escape = true)

/**
 * Generate a HTML link to a named route
 * @param string $name
 * @param string $title
 * @param array $parameters
 * @param array $attributes
 * @return \Illuminate\Support\HtmlString
 */
function link_to_route($name, $title = null, $parameters = [], $attributes = [])

/**
 * Generate a HTML link to a controller action
 * @param string $action
 * @param string $title
 * @param array $parameters
 * @param array $attributes
 * @return \Illuminate\Support\HtmlString
 */
function link_to_action($action, $title = null, $parameters = [], $attributes = [])

/**
 * Get the FormBuilder instance
 * @return \SpaanProductions\LaravelForm\FormBuilder
 */
function form()
```

#### Usage Examples

[](#usage-examples)

```
// In controllers
public function create()
{
    // Build a form element programmatically
    $cancelLink = link_to_route('users.index', 'Cancel', [], ['class' => 'btn btn-secondary']);

    return view('users.create', compact('cancelLink'));
}

// In views

    {!! link_to_route('users.index', 'Back to List', [], ['class' => 'btn btn-link']) !!}
    {!! link_to_asset('docs/manual.pdf', 'Download Manual', ['target' => '_blank']) !!}

// Using the form helper
@php
    $formInstance = form();
    $isModelSet = $formInstance->getModel() !== null;
@endphp
```

**Note:** Helper functions return `HtmlString` objects which are safe to echo directly without additional escaping.

### Blade Directives

[](#blade-directives)

The package automatically generates 50+ Blade directives for all public methods on the Form and HTML builders. Directives follow a simple naming convention: `@{builder}_{method}` in snake\_case.

**Available Directive Patterns:**

- Form directives: `@form_*` (e.g., `@form_text`, `@form_select`, `@form_checkbox`)
- HTML directives: `@html_*` (e.g., `@html_link`, `@html_script`, `@html_image`)

```
{{-- Form directives --}}
@form_open(['route' => 'users.store'])
    @form_text('name', null, ['class' => 'form-control'])
    @form_email('email')
    @form_date('birth_date')
    @form_select('country', $countries)
    @form_textarea('bio', null, ['rows' => 5])
    @form_checkbox('terms', 1, false)
    @form_submit('Create User')
@form_close()

{{-- HTML directives --}}
@html_link('users', 'View Users')
@html_link_route('users.show', 'Profile', ['user' => 1])
@html_script('js/app.js')
@html_style('css/app.css')
@html_image('logo.png', 'Logo')
@html_mailto('contact@example.com', 'Email Us')

{{-- Date/time directives --}}
@form_datetime_local('meeting', null, ['class' => 'form-control'])
@form_month('month')
@form_week('week')

{{-- Advanced directives --}}
@form_select_range('year', 2020, 2030)
@form_select_month('birth_month')
@form_datalist('browsers', ['Chrome', 'Firefox', 'Safari'])
```

**Note:** All directives echo their output automatically, just like `{{ }}` blade syntax.

Eloquent Integration
--------------------

[](#eloquent-integration)

### Using FormAccessible Trait

[](#using-formaccessible-trait)

Add the `FormAccessible` trait to your Eloquent models to enable form mutators. Form mutators allow you to transform model attributes specifically for display in forms, without affecting how they're stored or accessed elsewhere.

**Form Mutator Pattern:** `form{AttributeName}Attribute($value)`

```
