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

Pixelairport's avatar

Attach hasMany resource on update

Hi, I just read the nova docs resource section from "the basics" to "Authorization". I miss one thing, or maybe did not see it. There is a way to make Relations with HasMany::make('Roles') in fields. I use spatie permissions and i would like to give the admin the possiblity to attach roles to a user. Now i only see the roles on users index. But I want to attach roles to user in update section. I read https://nova.laravel.com/docs/3.0/resources/relationships.html#creating-inline-relations but is that only for belongsto? I have hasMany and nothing is shown in my form, when I add ->showCreateRelationButton() to my filed.

0 likes
4 replies
Pixelairport's avatar

Thx @lancashireman i did not know that. But this seems to be a package, which can handle all... permissions, roles, ... I will do the role stuff only via database (seeder) and not in nova. But I need the option to attach roles to user. I dont like to import packages for each little thing... and im not sure if this package is still updated. I had some problems with old packages in the past... so i try to avoid too much packages, if not really needed.

Pixelairport's avatar

Ok. I was my mistake. Now i have another problem. I used has many in nova but needed this:

BelongsToMany::make('Roles')

Now I have a table under users where i can detach and see all roles. But i cant attach a role. If i try i get this error:

SQLSTATE[HY000]: General error: 1364 Field 'model_type' doesn't have a default value (SQL: insert into `model_has_roles` (`model_id`, `role_id`) values (9, 2))

The mode_type is missing, but i dont know how to set it for the BelongsToMany field. Does anybody know this?

ps: Also when I click on edit a role in user resource, the roles field is disabled.

Pixelairport's avatar

I try it again, becuse I dont find the solution. I need realised that I havt to use MorphToMany::make('Roles')instead of BelongsToMany. But I still have the problem, that there is no model_type set. How can I set this up in my user resource that my MorphToMany Relation knows, what the model is. This is the error I still get: SQLSTATE[HY000]: General error: 1364 Field 'model_type' doesn't have a default value (SQL: insert into `model_has_roles` (`model_id`, `role_id`) values (6, 3))

Please or to participate in this conversation.