Possible issue with selects when using relationships #211
liamoreilly
started this conversation in
General
Replies: 3 comments 1 reply
-
Would like to know to! |
Beta Was this translation helpful? Give feedback.
0 replies
-
I have the same problem. |
Beta Was this translation helpful? Give feedback.
0 replies
-
i just sent PR #237 with the solution proposed by @liamoreilly |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
Let's say you are building an edit user page and want a multiselect for the roles a user has using the spatie/laravel-permission package (but it need not be this package, this issue would be the same with any relationship).
You provide the options array to the
html->multiselect
as an associative array of the form role ID to role name using some controller code of the form:Now let's say you have a
roles
relationship on your user model. In your create view you open a model form with this user as the model.One would expect the multiselect to be prepopulated with the correct roles for the user. However, this fails currently.
The issue boils down to Line 129 of laravel-html/tree/main/src/Elements/Select.php. Here,
$this->value
is an Eloquent Collection (Illuminate\Database\Eloquent\Collection
), emphasis on the Eloquent aspect. This collection of role models has been correctly pulled in from the user model. After this line executes,$value
is a normal Collection (Illuminate\Support\Collection
). Later on in Line 146 the contains method is called on this normal collection. This method behaves differently if the collection is a normal one or an Eloquent one. Each option's value is an integer/string. This integer/string fails to match the models in normal collections but it would match in Eloquent collections.As a note, 'old' values from failed validation work just fine as the
$value
collection is then a list of integer IDs. Only when retrieving them from the model are they a Collection of Role models.If Line 129 was wrapped in an "if not instance of Collection" then I suspect there would be no breakages, but this scenario would work out - there would be no need to turn it into a Collection if it is already a Collection and an Eloquent Collection would remain as one.
As a work around I could imagine creating a new attribute named something like
role_ids
and working with these, but this feels a bit dirty - for each occurrence of this scenario a separate attribute has to be created in the models.I recall this matching working as an Eloquent collection in laravelcollective/html. Either way, it makes this use-case particularly problematic (i.e., using a relationship with select/multiselect).
Any ideas? Maybe I am doing something fundamentally wrong here, but I currently don't see it.
Thanks,
Liam
Beta Was this translation helpful? Give feedback.
All reactions