laravel-form

Versie
7.3.1
Downloads
8.608 downloads
Licentie
MIT
GitHub

Basic Usage

Form Builder

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

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

// Text inputs
{{ Form::text('name', null, ['class' => 'form-control']) }}
// Generates: <input type="text" name="name" id="name" class="form-control">

{{ 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

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

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

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

// 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

{{ 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

// 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

// 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

// 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

{{ 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

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

Utility Methods

// HTML entity encoding/decoding
{{ Html::entities('<script>alert("XSS")</script>') }}  // 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

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

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

/**
 * 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

// 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
<div class="actions">
    {!! link_to_route('users.index', 'Back to List', [], ['class' => 'btn btn-link']) !!}
    {!! link_to_asset('docs/manual.pdf', 'Download Manual', ['target' => '_blank']) !!}
</div>

// 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

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.

Een fout gevonden of een vraag? Maak een issue aan op GitHub.