What is <form model="POST"> ...?
Invokable controller not being used on a form
Im using an invokable controller because I want to assign an ability to a role, and for this Im trying to pass the ID value of an ability, and then assign it to a role. In my database I have these tables:
- Roles
- Roles_user
- Abilities
- Ability_role
Ability_role table has 2 columns; role_id and ability_id here an ability is associated to a role.
I want to be able to write an association on this table by using a method that I have on my Role model which is this:
public function allowTo($ability)
{
$this->abilities()->sync($ability, false);
}
But I get a Not Found message and this on the URI:
http://videotheque.test/assignAbility?abilities[]=2
So it means the controller im using it's not being used. This is what I do and what I have:
- Through a select element, I print out the current abilities and then a button to submit the form
- The option value on the select, points to the ID stored in the database
- In my web routes I have an invokable controller being listed with a post method 4- On my ``AbilitiesRoleController``` I have created a method which should accept the request
- After the request is received, the role should now have a new ability assigned
roles-tab.blade.php
<form
action="/assignAbility"
model="POST"
>
<select
name="abilities[]"
id="abilities"
multiple
>
@foreach ($abilities as $ability)
<option value="{{ $ability->id }}">
{{ $ability->name }}
</option>
@endforeach
</select>
<button
type="submit">
Assign
</button>
</form>
web.php
Route::post('/assignAbility', AbilitiesRoleController::class);
AbilitiesRoleController.php
public function __invoke(Request $request, Role $role, Ability $abilities)
{
dd($abilities);
$abilities = request()->validate([
'ability_id' => ['required']
]);
foreach ($request->abilities as $ability) {
$role->allowTo($ability);
}
}
Whenever an ability has been selected and submitted through the form the method from AbilitiesRoleController.php should receive this data and write on the database, assigning a new ability to a particular role.
Instead a 404 page is displayed and I notice that the URI shows this: http://videotheque.test/assignAbility?abilities[]=2 which seems to me that the controller that I assign on the routes, is not even being used correctly so the method is not even called.
It's a Laravel 8 project. Thanks!
What is the purpose of the typehinted Role in the method signature; there is no corresponding wildcard segment{role} in the URI, e.g.
Route::post('roles/{role}/assignAbility', AbilitiesRoleController::class);
<form action="/roles/{{ $role->id }}/assignAbility" method="POST">
Please or to participate in this conversation.