Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ignium's avatar
Level 21

Access AttributesBag in component class?

Is it possible to access the attributes bag on the class behind a component? I'm trying to calculate a default value based on the value passed to the "name" attribute on an input.

In Input.php

    protected function getField($field)
    {
        if (null == $field && null == $this->attributes['name']) return null;

        return $field ?? Str::of($this->attributes['name'])
					->afterLast('.')->__toString();
    }

Which results in the following error Trying to access array offset on value of type null.

I've also tried $this->name (both before and after creating a public property) and $attributes['name'] as well.

I'm not 100% sure how the order of things is called and if it's even possible to get access to the attributes.

As a side note: adding dump($this) in the render() method results in the following and attributes is always null (even though the component I used to test this had, 'required', 'name' and 'placeholder' set)

App\View\Components\forms\Input {#1792 ▼
  #model: null
  #field: null
  #method: null
  #except: []
  +componentName: "forms.input"
  +attributes: null
}
0 likes
3 replies
Amaury's avatar

You just have to declare the attribute as a public property and pass the value in the constructor. il will be accessible in the class:


public $name;

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

If you use anonymous components, you can add a prop 'name' to isolate the attribute from the attributes bag and make any condition with the $name value


@props(['name'])

// conditions with $name value...

<input  name="{{ $name }}" {{ $attributes }} ... />

Or you can create a dynamic component (with Laravel 8)


@props(['name'])

<x-dynamic-component :component="input.$name" {{ $attributes }} />

prajwalhallale's avatar

You can access the $attributes array in the components render method something like this

public function render(): 
    {
        return function (array $data) {
            dd($data['attributes']);
            return view('component.name');
        };
    }
coderapers's avatar

@prajwalhallale

You can access to attributes by extending Illuminate\View\Component class like this:

You can process component's logic by realisation of method App\Lib\Component::processArguments() in child classes in App\View\Components namespace.

Please or to participate in this conversation.