简体   繁体   English

在 laravel 中为未登录用户授权资源

[英]authorizeResource for not logged-in users in laravel

While in policy class I have在政策课上我有

public function create(User $user)
{
    return true;
}

but I get unauthorized error for unauthenticated users.但我收到未经身份验证的用户未经授权的错误。

So how can I exclude the store method from authorization in authorizeResource?那么如何从authorizeResource中的授权中排除store方法呢?

To be able to use guest users with Laravel's authorisation you simply need to type-hint that the user is nullable:为了能够在 Laravel 的授权下使用来宾用户,您只需键入提示该用户可以为空:

public function create(?User $user)
{
    return true;
}

or you can set the default value to null或者您可以将默认值设置为 null

public function create(User $user = null)
{
    return true;
}

For more information you can check the documentation有关更多信息,您可以查看文档

If you are adding your route is located inside a group that forces auth middleware you just need to get it out of this group:如果您添加的路由位于强制身份验证中间件的组内,则只需将其从该组中取出:

Route::post('company/create', 'CompanyController@create');
Route::group(['middleware' => 'auth'], function () {
  //Your authenticated routes
  Route::apiResource('companyregister' , 'CompanyRegisterController')->except(['update', 'create']);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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