Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel 8, how to pass form values to Route

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');

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading