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 9 – Get User ID for user management

I’m creating a users management with Laravel 9, I am an administrator and I would like to change users to admins whenever I like 🙂

For example this user ->

enter image description here

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

I wrote this code ->

        public function UpdateToAdminAction(Request $request) {

        $request->validate([
            'type' => 'required|exists:users',
        ]);

        DB::table('users')->update(
            ['type' => $request->type]
        );

        return redirect('/gestion-administrateurs');
    }

But I cannot update THIS user’s type, this code changes ALL users’ types lol, it’s not what I wanted. Do you know with this code, how can I change THIS user’s type ?

Thanks, I hope you’ll understand my request ^^

>Solution :

You need to pass user ID as route part, or as request param

For example, you may create following route for updating users:

// Dont forget to protect this route with middleware like "can:edit-users"!
Route::post('/user/{id}', 'UserController@update');

then, render in template button to made user admin:

<form method="post" action="/user/{{ $user->id }}">
    @csrf
    <input type="hidden" name="type" value="admin">
    <button type="submit">Make admin</button>
</form>

And create update method:

public function update(Request $request)
{
    $request->validate([
        'type' => 'required|exists:users',
    ]);

    DB::table('users')
        ->where('id', $request->id)
        ->update(
            ['type' => $request->type]
        );

    return redirect('/somewhere');
}
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