首页 > 解决方案 > 如何从 laravel 中的任何模型和控制器中获取计算变量?

问题描述

我有 2 个模型:UserAccount

帐户是公司帐户,它有一个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*/...

标签: phplaravel

解决方案


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');

推荐阅读