Laravel 速查表
显示全部 1. Artisan 2. Auth 3. Blade 4. Cache 5. Collection 6. Composer 7. Config 8. Container 9. Cookie 10. DB 11. Environment 12. Event 13. File 14. Form 15. HTML 16. Helper 17. Input 18. Lang 19. Log 20. Mail 21. Model 22. Pagination 23. Queue 24. Redirect 25. Request 26. Response 27. Route 28. SSH 29. Schema 30. Security 31. Session 32. String 33. URL 34. UnitTest 35. Validation 36. View
Menu

Auth

未匹配的标注
本文档最新版为 9.x,旧版本可能放弃维护,推荐阅读最新版!

用户认证

// 判断当前用户是否已认证(是否已登录)
 Auth::check();
// 获取当前的认证用户
 Auth::user();
// 获取当前的认证用户的 ID(未登录情况下会报错)
 Auth::id();
// 通过给定的信息来尝试对用户进行认证(成功后会自动启动会话)
 Auth::attempt(['email' => $email, 'password' => $password]);
// 通过 Auth::attempt() 传入 true 值来开启 '记住我' 功能
 Auth::attempt($credentials, true);
// 只针对一次的请求来认证用户
 Auth::once($credentials);
// 登录一个指定用户到应用上
 Auth::login(User::find(1));
// 登录指定用户 ID 的用户到应用上
 Auth::loginUsingId(1);
// 使用户退出登录(清除会话)
 Auth::logout();
// 验证用户凭证
 Auth::validate($credentials);
// Attempt to authenticate using HTTP Basic Auth
 // 使用 HTTP 的基本认证方式来认证
 Auth::basic('username');
// Perform a stateless HTTP Basic login attempt
 // 执行「HTTP Basic」登录尝试
 Auth::onceBasic();
// 发送密码重置提示给用户
 Password::remind($credentials, function($message, $user){});

用户授权

// 定义权限
 Gate::define('update-post', 'Class@method');
Gate::define('update-post', function ($user, $post) {...});
// 传递多个参数
 Gate::define('delete-comment', function ($user, $post, $comment) {});

// 检查权限
 Gate::denies('update-post', $post);
Gate::allows('update-post', $post);
Gate::check('update-post', $post);
// 指定用户进行检查
 Gate::forUser($user)->allows('update-post', $post);
// 在 User 模型下,使用 Authorizable trait
 User::find(1)->can('update-post', $post);
User::find(1)->cannot('update-post', $post);

// 拦截所有检查
 Gate::before(function ($user, $ability) {});
Gate::after(function ($user, $ability) {});

// Blade 模板语法
 @can('update-post', $post)
@endcan
// 支持 else 表达式
 @can('update-post', $post)
@else
@endcan

// 生成一个新的策略
php artisan make:policy PostPolicy
// `policy` 帮助函数
policy($post)->update($user, $post)

// 控制器授权
$this->authorize('update', $post);
// 指定用户 $user 授权
$this->authorizeForUser($user, 'update', $post);

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~