Laravel 5.6 - 检查用户是否可以根据请求参数创建记录

Laravel 5.6 - check if user can create record based on request parameter

在我的应用程序中,用户可以创建按相关组织者 ID 分类的活动。

我想检查提交创建新活动请求的用户是否有权访问他们为其创建活动的组织者。

例如:

$organiser_id = $request->input('organiser_id');
if($user->hasOrganiser($organiser_id)) {
    // User has permission
}

显然以上内容可以在我的控制器中使用,但理想情况下我想在我的 EventPolicy class 或 EventRequest 中实现。

在此先感谢您的帮助。

我正在旅行,但我认为这会对你有所帮助。

Laravel 使用名为 Auth 的 class,因此您可以像这样调用 class staticky:Auth::id()

更多信息: https://laravel.com/docs/5.6/authentication

希望对您有所帮助。

Laravel 提供了很多方法来完成这个,你可以随时查看文档,在文档中你会发现控制器(你可以排除)、模型和中间件中的检查。

勾选 authorizing-actions-using-policies

您可以随时使用 middleware which handles the HTTP requests before hitting your app isntance,从而更好地控制您的应用程序。

Laravel includes a middleware that can authorize actions before the incoming request even reaches your routes or controllers. By default, the Illuminate\Auth\Middleware\Authorize middleware is assigned the can key in your App\Http\Kernel class.

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    if ($request->age <= 200) {
        return redirect('home');
    }

    return $next($request);
}

按照 link 的说明将其添加到 route file,这样您就可以检查请求并部署保护措施。

Route::post('/post', function () {
// The current user may create posts...
})->middleware('can:create,App\Post');

您也可以在第一个link中查看模型方式。