「这是我参与11月更文挑战的第13天,活动详情查看:2021最后一次更文挑战」
本篇对Laravel常用技巧进行汇总,如果大家想了解某一个分支下的使用技巧,比如集合、Eloquent等可以查看我之前的文章。
日志记录参数
我们可以使用 Log::info(),或使用更短的 info() 额外参数信息,来了解更多发生的事情
Log::info('User failed to login.', ['id' => $user->id]);
更方便的 DD
我们可以在 Eloquent 句子或者任何集合结尾添加 ->dd(),而不是使用 dd($result)。
// 以前
$users = User::where('name', '小明')->get();
dd($users);
// 现在
$users = User::where('name', '小明')->get()->dd();
使用 context 日志
在最新的 Laravel 8.49 中:Log::withContext() 将帮助我们区分不同请求之间的日志消息。
如果我们创建了中间件并且设置了 context,所有的长消息将包含在 context 中,我们搜索会更容易。
举例:
public function handle(Request $request, Closure $next)
{
$requestId = (string) Str::uuid();
Log::withContext(['request-id' => $requestId]);
$response = $next($request);
$response->header('request-id', $requestId);
return $response;
}
API 资源:带不带 “data”?
如果我们使用 Eloquent API 去返回数据,它们将自动封装到 data 中。
如果要将其删除,需要在
app/Providers/AppServiceProvider.php
中添加 JsonResource::withoutWrapping()
;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
JsonResource::withoutWrapping();
}
}
API 返回一切正常
如果我们有 API 端口执行某些操作但是没有响应,我们只想返回 “一切正常”: 我们可以返回 204 状态代码 “No content”。
在 Laravel 中,这就很简单: return response()->noContent();.
public function reorder(Request $request)
{
foreach ($request->input('rows', []) as $row) {
Country::find($row['id'])->update(['position' => $row['position']]);
}
return response()->noContent();
}
一次检查多个权限
除了 @can Blade 指令外,还可以用 @canany 指令一次检查多个权限:
@canany(['update', 'view', 'delete'], $articles)
// 当前用户可以修改,查看,或者删除文章
@elsecanany(['create'], \App\Article::class)
// 当前用户可以创建文章
@endcanany
更多关于用户注册的事件
希望在新用户注册后执行一些操作怎么优雅的实现呢?
我们可以转到 app/Providers/EventServiceProvider.php
和 添加更多的监听类,
然后在 $event->user 对象中实现 handle() 方法。
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
// 我们可以在这里添加任何Listener类
// 在该类中使用handle()方法
],
];
Auth::once () 的使用
使用方法 Auth::once(),可以用用户登录一个请求。 Auth::once () 不会使用任何会话或 cookie,这意味着该方法在构建无状态 API 时可能很有帮助。
if (Auth::once($credentials)) {
//
}
更改用户密码更新的 API 令牌
当用户的密码更改时,可以方便地更改用户的 API 令牌。
这个实现非常重要
模型:
public function setPasswordAttribute($value)
{
$this->attributes['password'] = $value;
$this->attributes['api_token'] = Str::random(100);
}
覆盖超级管理员的权限
如果你已经定义了网关(Gates)但是又想要覆盖超级管理员的所有权限。
给超级管理员所有权限,我们可以在 AuthServiceProvider.php 文件中用 Gate::before() 语句拦截网关(Gates)。
// 拦截任何一个网关,检查它是否是超级管理员
Gate::before(function($user, $ability) {
if ($user->is_super_admin == 1) {
return true;
}
});
// 或者你使用一些权限包
Gate::before(function($user, $ability) {
if ($user->hasPermission('root')) {
return true;
}
});
Last but not least
技术交流群请到 这里来。 或者添加我的微信 wangzhongyang0601 ,一起学习。
感谢大家的点赞、评论、关注,谢谢大佬们的支持,感谢。