Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
1️⃣ Is this something that is wanted/needed? Did you create a discussion about it first?
It's something I'd personally find useful, and imagine others would too. No discussion though.
2️⃣ Did you create a branch for your fix/feature? (Main branch PR's will be closed)
Yes:
required-attribute
3️⃣ Does it contain multiple, unrelated changes? Please separate the PRs out.
No, just this feature.
4️⃣ Does it include tests? (Required)
Yes
5️⃣ Please include a thorough description (including small code snippets if possible) of the improvement and reasons why it's useful.
Motivation
Due to the way attributes on Livewire components are set on the component's properties (i.e. not through a constructor), properties without default values can be left uninitialized if the corresponding attributes are missing from the component tag.
This can cause any number of different errors depending on how the property is used. Commonly something like:
Attempt to read property "foo" on null
Typed property Foo::$bar must not be accessed before initialization
These errors generally aren't too difficult to diagnose, but if another developer wrote the component, and particularly if the property is used in a less straightforward way (e.g. within an Alpine component), it can become much less obvious what is causing the error.
Also, there is no distinction between properties that need to be passed to the component, and properties that are simply set within the component itself (via actions etc.). So, again if another developer wrote the component, it's not always clear what needs to be passed via attributes unless it is documented.
Solution
This PR adds a simple
#[Required]
attribute that can be added to properties that should be passed to the component. If any required attributes are missing, an error will be thrown on mount: