Yachi 웃 Yachi 웃 - 2 months ago 11
PHP Question

Add one more option in select element using Illuminate\html

I have a create method like this:

public function create()
{
$categories = App\CategoryModel::pluck('name', 'id');
return view('posts.create', compact('categories'));
}


and I want to add some options to select element using
Illuminate\html
.

This is my select element:

{!! Form::label('category', 'Category') !!}
{!! Form::select(null, $categories, null, ['class' => 'form', 'style' => 'height: 40px;', 'name' => 'category']); !!}


But I want to add one more option element like this:

<option disabled selected> -- Select a category -- </option>


What should I do?

Answer Source

You can create your custom macro to fulfill this. Check below step by code:
1) Create macro under app/lib/macro.php

<?php
//My custom macro...
Form::macro('mySelect', function($name, $list = array(), $selected = null, $disabled = null, $options = array())
{
    $selected = $this->getValueAttribute($name, $selected);
    $disabled = $this->getValueAttribute($name, $disabled);

    $options['id'] = $this->getIdAttribute($name, $options);

    if ( ! isset($options['name'])) $options['name'] = $name;

    $html = array();

    foreach ($list as $list_el)
    {
        $selectedAttribute = $this->getSelectedValue($list_el['id'], $selected);
        $disabledAttribute = $this->getSelectedValue($list_el['id'], $disabled);
        $option_attr = array('value' => e($list_el['id']), 'selected' => $selectedAttribute, 'disabled' => $disabledAttribute);
        $html[] = '<option'.$this->html->attributes($option_attr).'>'.e($list_el['value']).'</option>';
    }

    $options = $this->html->attributes($options);

    $list = implode('', $html);

    return "<select{$options}>{$list}</select>";
});

2) Register macro into app/Providers/MacroServiceProvider.php

<?php

namespace App\Providers;

use App\Services\Macros\Macros;
use Collective\Html\HtmlServiceProvider;

/**
 * Class MacroServiceProvider
 * @package App\Providers
 */
class MacroServiceProvider extends HtmlServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        require base_path() . '/app/lib/macro.php';
    }

.
.
.
}

3) Use my custom macro:

{!!Form::mySelect('category',array(array('id' => '0', 'value'=>'-- Select a category --'), array('id' => '1', 'value'=>'My value1'), array('id' => '2', 'value'=>'My value2')), 0, 0) !!}

Hope you get the idea about custom macro. Tested with laravel 5.2