Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Laravel 7 component programmatically

I have a Laravel 7 component which looks like this

class Input extends Component
{
    public $name;
    public $title;
    public $value;
    public $type = 'text';

    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct($name, $title)
    {
        $this->name = $name;
        $this->title = $title;
        $this->value = \Form::getValueAttribute($name);
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view('components.fields.input');
    }
}

I can render the field in my Blade component like this:

<x-input name="name" :title="__('My field')" />

I have a requirement to create and render the field in code, I've tried the following:

$field = new Input('name', 'My field');
$field->render();

This returns an error:

Undefined variable: title

I can see that the render function is called but the public properties are not made available to the view. How would I render the component with the public properties?

like image 648
Dan Avatar asked Jan 01 '23 03:01

Dan


1 Answers

Try this, it works for me in laravel 8, and I checked data function exists in laravel 7

$field = new Input('name', 'My field');
$field->render()->with($field->data());

** data function include methods, properties and attributes of Component.

like image 157
Huynh Trinh Avatar answered Jan 05 '23 10:01

Huynh Trinh