我正在學習Laravel 5.我已完成文檔的Quickstart - intermediate。我想將任務的操作的授權檢查應用於用戶。我想檢查目標用戶是否是當前登錄用戶,以便使用用戶的編輯操作。然而,瀏覽器不斷告訴我,當我嘗試訪問http://myfirst.app/users/2/edit
:Handler.php中的HttpException第107行:此操作未經授權
FatalThrowableError in UsersPolicy.php line 20:
Type error: Argument 1 passed to App\Policies\UsersPolicy::edit() must be an instance of Illuminate\Http\Request, instance of App\User given
routes.php文件
Route::get('/users/{user}', '[email protected]');
Route::get('/users/{user}/edit', '[email protected]');
Route::patch('/users/{user}', '[email protected]');
AuthServiceProvider.php
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
'App\Task' => 'App\Policies\TaskPolicy',
'App\User' => 'App\Policies\UsersPolicy',
];
UsersPolicy.php
namespace App\Policies;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Auth\Access\HandlesAuthorization;
class UsersPolicy
{
use HandlesAuthorization;
public function edit(Request $request, User $user)
{
return $request->user()->id === $user->id;
}
public function update(Request $request, User $user)
{
return $request->user()->id === $user->id;
}
}
UsersControl
TaskController.php
public function destroy(Task $task)
{
$this->authorize('destroy', $task);
$task->delete();
return redirect('/tasks');
}
TaskPolicy:ler.php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UsersController extends Controller
{
protected $user;
public function __construct() {
$this->middleware('auth');
}
public function view(Request $request, User $user)
{
if($request->user()->id == $user->id){
return view('users.view', ['user' => $user]);
}
return redirect('/tasks');
}
public function edit(Request $request, User $user)
{
$this->authorize('edit', $user);
return view('users.edit', compact('user'));
}
public function update(Request $request, User $user)
{
$this->authorize('update', $user);
$user->update($request->all());
return redirect('/users/'.$user->id);
}
}
在Document's TaskController的刪除功能,$user
不是爲了讓TaskPolicy的破壞功能使用$user
傳遞到$this->authorized('destroy', $task)
.php
public function destroy(User $user, Task $task)
{
return $user->id === $task->user_id;
}
反正,我跟着異常,並添加$請求UsersController的編輯功能的參數
$this->authorize('edit', $request, $user);
我也得到
HttpException in Handler.php line 107:
This action is unauthorized.
我應該怎麼辦?