phplaravel-8laravel-components

laravel - passing data to class-based component, without @props


I have this component:

class CategorySelect extends Component
{

    public $id_name, $selected;

    public function __construct($selected=-1, $id_name="default_id")
    {
        $this->id_name = $id_name;
        $this->selected = $selected;
    }

    public function render()
    {
        return view('components.category-select', ['categories' => Category::all()]);
    }
}


<select name="{{ $id_name }}" id="{{ $id_name }}">
    @foreach ($categories as $c)
        @php
            $s = $c->id == $selected ? 'selected=selected' : '';
        @endphp
        <option {{ $s }} value="{{ $c->id }}">{{ $c->title }}</option>
    @endforeach
</select>

I use it like this:

<x-category-select selected="old('category_id', $article->category_id)" 
                   id_name="category_id"></x-category-select>

The $selected is passed and working, but the $id_name stays in its default value from the constructor. changing to :id_name="category_id" fails with Undefined constant "category_id"

What is the proper way to do it, without @props() (I'm using class based components and not anonymous components for that reason, among others..)?


Solution

  • If anyone will stumble on it in the future - the issue was the naming convention. when the variable names changed to camelCase - it worked.

    $id_name changed to $idName and it worked