简体   繁体   中英

Laravel 5.4 change user role

I trying make changing role in my panel admin. But when i made it my form dont sending post request. Now only working showing user role. I cant fix it becouse when i click button to switch i dont get any error and role is not changing.

I use HttpRequester when i use url /admin/change its showing this error: MethodNotAllowedHttpException in RouteCollection.php line 233

There is my code:

View:

 @extends('layouts.app') @section('content') <h2>Panel Admina</h2> <div class="panel-group"> <div class="panel panel-default"> <div class="panel-body"> <table class="table"> <thead> <tr> <th>Id</th> <th>Imię</th> <th>Nazwisko </th> <th>E-mail </th> <th>Nr.tele </th> <th>Użytkownik </th> <th>Moderator </th> <th>Admin </th> </tr> </thead> <tbody> @foreach($users as $user) <tr> <form action="{{route('change')}}" method="post"> {{ csrf_field() }} <td>{{ $user->id }}</td> <td>{{ $user->name }}</td> <td>{{ $user->lastname }}</td> <td>{{ $user->email }}<input type="hidden" name="email" value="{{ $user->email }}"></td> <td>{{ $user->phonenumber }}</td> <td><input type="checkbox" {{ $user->hasRole('User') ? 'checked' : '' }} name="role_user"/></td> <td><input type="checkbox" {{ $user->hasRole('Moderator') ? 'checked' : '' }} name="role_moderator"/></td> <td><input type="checkbox" {{ $user->hasRole('Admin') ? 'checked' : '' }} name="role_admin"/></td> <td><input type="submit" class="btn btn-default btn-sm" value="Przydziel rolę"></td> </form> </tr> @endforeach </tbody> </table> </div> </div> </div> @endsection 

Controller:

  public function change(Request $request) { $user = User::where('email', $request['email'])->first(); $user->roles()->detach(); if ($request['role_user']) { $user->roles()->attach(Role::where('name', 'User')->first()); } if ($request['role_moderator']) { $user->roles()->attach(Role::where('name', 'Moderator')->first()); } if ($request['role_admin']) { $user->roles()->attach(Role::where('name', 'Admin')->first()); } return redirect()->back(); } 

Routing:

 Route::get('/admin', [ 'uses' => 'AdminController@index', 'middleware' => 'roles', 'roles' => ['Admin'] ]); Route::post('/admin/change', [ 'uses' => 'AdminController@change', 'as' => 'change', 'middleware' => 'roles', 'roles' => ['Admin'] ]); 

I really dont know how i can resolve my problem.

try to pass the user id to your route and your form action and instead of post make it put for example:

<form action="{{route('change', $user->id)}}" method="post">

and in your route:

Route::put('/admin/change/{id}', [
    'uses' => 'AdminController@change',
    'as' => 'change',
    'middleware' => 'roles',
    'roles' => ['Admin']
]);

and in your controller:

public function change(Request $request, $id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM