Get data from parent component - laravel7

1.2k views Asked by At

I'm struggling with an issue.

I want to create a form builder with laravel's new x-component syntax but i couldn't get data from parent component

blade file:

<x-input name="email">
    <x-email>{{ __('E-mail Address') }}</x-email>
</x-input>

components/form/inputs/master.blade.php:


<div class="form-group">
    {{ $slot }}
</div>

components/form/inputs/email.blade.php:

<input type="email" class="form-control" placeholder="{{ $placeholder ?? $slot }}" name="{{ $name }}">

throws : \ViewException Undefined variable: name

I can get name attribute in email like : <x-email name="email"/> but I don't want to do that. Because I may have at least 20+ kind of inputs like password, text, select etc.

I'm planing to use <x-input/> for general purposes like validation messages, labels etc. and each x-* contain specific attributes like :options for x-select, :checked for checkbox or radio...

Components\Input.php :

<?php

namespace App\View\Components\Form;

use Illuminate\View\Component;

class Input extends Component
{
    public $name;
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct($name)
    {
        $this->name = $name;
    }

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

Components\Email.php:

<?php

namespace App\View\Components\Input;

use Illuminate\View\Component;

class Email extends Component
{

    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct()
    {

    }

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

If I inject $name to Email.php in constructor it says unresolved dependency $name.

1

There are 1 answers

0
Amade On

It's not possible. You need to explicitly pass any data you want accessible in a view component. The only exception is global/shared data injected with View Composers.