Home > Software design >  Laravel 8, how to pass form values to Route
Laravel 8, how to pass form values to Route

Time:11-28

I am doing roles&permissions, an action that admin can change user to staff. I am able to send id to editRolePermission function, but the role value.

    function editRolePermission($id, "role value here")
    {

        $row = DB::table('users')
                ->where('id',$id)
                ->limit(1)
                ->update(array('role' => ''));
        return redirect()->back();
    }
<form action="{{ route('updateRolePermission', $user->id) }}" method="POST">

    @method('PATCH')
    @csrf

    <select name="roles">
    <option name ="user" value="user">User</option>
    <option name= "staff" value="staff">Staff</option>
    </select>
    <input type="submit" onchange="this.form.submit()">
</form>
Route::patch('edit-role-permission/{id}', [AdminController::class, 'editRolePermission'])->name('updateRolePermission');

CodePudding user response:

The following should do what you want. Here is the route - notice I have swapped {id} for {user} - this is the ID of the user we need to edit the role for:

Route::post("/edit-role-permission/{user}", [AdminController::class, "editRolePermission"]);

How to implement the route in your form:

@if(session()->has("message"))
    {{ session("message") }}
@endif

<form action="/edit-role-permission/{{ $user->id }}" method="POST">
    @csrf

    <select name="roles">
        <!-- ... options ... -->
    </select>

    <!-- submit button -->
</form>

Thanks to Laravel magic, passing the user ID as the second parameter allows us to access the user model so we can update the user easily, with a lot less code. We can use the request to get any posted values, in this instance $request->roles refers to the input named roles:

public function editRolePermission(Request $request, \App\Models\User $user)
{
    $user->update(["role" => $request->roles]);
    $user->save();

    return redirect()->back()->with("message", "User role updated successfully");
}
  • Related