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 ->
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 ^^
CodePudding user response:
you are selecting all the users by this query DB::table('users')
,
assuming you are receiving id in request
you must select one row by adding a where condition DB::table('users')->where('id',$request->id)->update(['type' => $request->type])
CodePudding user response:
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');
}