laravel - 改善 Laravel 中的 if else 条件
问题描述
我有一个 Laravel 项目,两天后就要上线了。我在后端和前端运行了很多查询。我正在努力提高应用程序的速度,因为现场制作中会有更多的用户。在我的控制器中,我经常使用此代码。
public function createCutting()
{
if (Auth::user()->admin == 0 && Auth::user()->roles()>first()>pivot->role_id == 7)
{
$type_of_cuts = Type::where('field', 2)->get();
$type_of_damages = Type::where('field', 3)->get();
$number_of_boxes = Type::where('field', 4)->get();
$size_of_boxes = Type::where('field', 5)->get();
return view('web.cutting.working_orders.create', compact('type_of_cuts', 'type_of_damages', 'number_of_boxes', 'size_of_boxes'));
} else {
return redirect()->route('working.orders.index')->with('alert', 'You cannot access this page');
}
刀片视图是这个
@if ($admin != 1)
@if ($role_id == 7)
<a href="{{ route('cutting.working.orders.create') }}" class="btn btn-label-brand btn-bold">
<i class="la la-plus"></i> Create Cutting</a>
@endif
@if ($role_id == 6)
<a href="{{ route('packaging.working.orders.create') }}" class="btn btn-label-brand btn-bold">
<i class="la la-plus"></i> Create Packaging</a>
@endif
@endif
@endif
看看代码中的 if 条件我必须先在控制器中的两个地方使用它,然后在前端使用它(在控制器中隐藏此方法的链接)。有没有更好的方法在一个地方使用条件而不在应用程序中运行两次相同的查询?也许喜欢使用中间件左右。问候,
解决方案
您正在尝试做的是幻数和冗长编程的混合。这是你的代码:
@if ($admin != 1)
@if ($role_id == 7)
<a href="{{ route('cutting.working.orders.create') }}" class="btn btn-
label-brand btn-bold">
<i class="la la-plus"></i> Create Cutting</a>
@endif
@if ($role_id == 6)
<a href="{{ route('packaging.working.orders.create') }}" class="btn btn-
label-brand btn-bold">
<i class="la la-plus"></i> Create Packaging</a>
@endif
@endif
@endif
您应该像这样使用 Spatie Blade 指令:
//if the user is an admin he/she can perform the action.
@hasrole('admin')
//Granting different admin users different permissions.
@can('create cutting order')
// only the admin who can create cutting...
<a href="{{ route('cutting.working.orders.create') }}"></a>
@endcan
@can('create packaging order')
// only the admin who can create packaging...
<a href="{{ route('packaging.working.orders.create') }}"></a>
@endcan
@else
//he/she is not an admin, then he/she is not allowed to do anything.
@endhasrole
推荐阅读
- sql - 如何返回日期字段添加两天而不影响原始日期?
- android - E/com.facebook.appevents.RestrictiveDataManager:updateRulesFromSetting 失败
- c# - 如何获取登录用户名
- spring-boot - 无需重定向到 Keycloak 的客户端身份验证
- c# - 我会找出接下来几天的日期
- prestashop - “取消分组”产品功能
- python - 使用子进程库:错误:无法识别的参数
- c++ - “不能从 'std::ofstream {aka std::basic_ofstream
}' to bool" 错误作为回报 - laravel - 无法更新第一次创建以外的其他表行
- solr - 索引多个文档