php - 如何从 laravel 中的任何模型和控制器中获取计算变量?
问题描述
我有 2 个模型:User和Account。
帐户是公司帐户,它有一个slug
字段。需要 Slug 来确定用户正在访问哪个公司。例如,路线/account/*company_slug*/deals
意味着用户试图获得company_slug公司的一系列交易。
与公司关联的每个实体都有一个字段account_id
。这就是为什么我需要获得一个经常账户。我应该在哪里以及如何做?
CheckIfAccountAcceptedForUser
例如,我使用以下代码获取中间件:
public function handle($request, Closure $next)
{
$account = Account::find($request->route()->parameter('account'));
abort_if(empty($account), 404) ;
abort_if(DB::table('account_user')
->where(function (Builder $query) use ($account) {
$query->where('account_slug', '=', $account->slug);
$query->where('user_id', '=', Auth::id());
})
->get()
->isEmpty(), 403);
return $next($request);
}
如果路由是这样的,如何为我的应用程序全局设置 account_id /account/*account*/...
?
解决方案
public function handle($request, Closure $next)
{
$account = Account::find($request->route()->parameter('account'));
abort_if(empty($account), 404) ;
abort_if(DB::table('account_user')
->where(function (Builder $query) use ($account) {
$query->where('account_slug', '=', $account->slug);
$query->where('user_id', '=', Auth::id());
})
->get()
->isEmpty(), 403);
//For global use in your all view file
View::share ( 'account_id', $account->id);
// to access account_id in controller
$request->request->add(['account_id' => $account->id]);
return $next($request);
}
在控制器中
$account_id = request('account_id');
推荐阅读
- ios - 从 Firebase 打印所有子列 - iOS Swift 4
- google-apps-script - 如何使用 App Scripts 中的 Drive API v3 实现锚点?
- spring-boot - 使用 Spring-Kafka 等待消息的 API
- rust - frunk 的 foldl 针对具有不同类型参数具有相同特征的元素
- java - 这个概念叫什么?
- php - MySQL,如何获取具有最高后缀的字符串
- linux - 用于克隆 GitHub 存储库的 Shell 脚本
- python - Tkinter 小部件颜色不会改变
- c# - 如何在 C# 中使用字符串键和值创建字符串多维数组?
- verilog - verilog 代码在 isim(xilinx 14.2) 中工作,但在 onspartan6 上不工作