laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Specifying props and classes inside the blade component class #2583

Closed bastinald closed 3 years ago

bastinald commented 3 years ago

It would be nice if we could specify our props and classes inside of blade component classes to keep our views cleaner.

For example:

<?php

namespace App\View\Components\Forms;

use Illuminate\View\Component;

class Input extends Component
{
    public $error;

    public function __construct($error)
    {
        $this->error = $error;
    }

    public function props()
    {
        return [
            'type' => 'text',
            'inputmode' => 'text',
        ];
    }

    public function classes()
    {
        return [
            'w-full rounded',
            !$this->error => 'border-gray-400',
            $this->error => 'border-red-600',
        ];
    }

    public function render()
    {
        return view('components.forms.input');
    }
}

Then in the view:

<div>
    <input {{ $attributes->merge() }}>

    @if($error)
        <p class="text-red-600">{{ $error }}</p>
    @endif
</div>

If there is already a way to do this please let me know.

bastinald commented 3 years ago

This is close but still not as clean:

    public function render()
    {
        return function ($data) {
            $attributes = $data['attributes']->class([
                'w-full rounded-lg placeholder-gray-400 border-gray-400 mb-4'
            ])->merge([
                'type' => 'text',
            ]);

            return <<<HTML
                <input $attributes>
            HTML;
        };
    }