gpt4 book ai didi

php - Laravel 5 新的身份验证 : Get current user and how to implement roles?

转载 作者:IT王子 更新时间:2023-10-28 23:55:44 26 4
gpt4 key购买 nike

我目前正在试验新的 Laravel 5 并让身份验证工作(注册/登录)。

为了在我的 Controller 中获得经过身份验证的用户,我目前将 Guard 注入(inject)到 Controller 操作中:

use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;

class ClientController extends Controller {

/**
* Display a listing of the resource.
*
* @return Response
*/
public function index(Guard $auth)
{
return view('client.index', ['user' => $auth->user()]);
}
...

第一个问题:这是推荐的方式吗?

第二个问题:我将如何实现某种角色/权限?像 client.edit, client.add, ... Larval 5 在这里提供某种便利吗?我将如何为路由/ Controller 操作设置必要的角色/权限?

我在想我可能需要为此编写自己的中间件。关于如何解决这个问题有什么建议吗?

最佳答案

在 Laravel 5 上花了一些时间后,我可以回答我自己的问题:

注入(inject) Guard 是推荐的方式吗? 否:如果你需要在你的 View 中访问 Auth,你已经可以这样做了:

@if( Auth::check() )
Current user: {{ Auth::user()->name }}
@endif

这使用 Auth 外观。所有可用外观的列表在 config/app.php 中的 aliases:

如果我在 Controller 中需要 Auth 怎么办? 像问题中所示注入(inject) Guard 的实例有效,但您不需要需要。您可以像在模板中那样使用 Auth 外观:

    public function index()
{
if(\Auth::check() && \Auth::user()->name === 'Don') {
// Do something
}
return view('client.index');
}

请注意,由于 L5 使用命名空间,因此在外观名称之前需要 \

我想使用 L5 中的新身份验证机制获得权限/角色: 我使用新的中间件实现了一个轻量级权限模块,它被称为 Laraguard。在 Github 上查看并告诉我您的想法:https://github.com/cgrossde/Laraguard

更新:为了完整起见,我想再提两个项目。它们提供了您在数据库中保存角色和权限所需的一切,并与 Laraguard 完美地协同工作或单独工作:

关于php - Laravel 5 新的身份验证 : Get current user and how to implement roles?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27571573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com