【问题标题】:Laravel session are not collectly filledLaravel 会话未收集填充
【发布时间】:2019-01-03 00:31:31
【问题描述】:

我遇到了以下问题:我的 laravel 应用程序中有切换器,它向控制器发出请求,控制器实际上设置了表单输入中传递的会话参数并返回 back() 响应。问题是有时它被错误地填充并混合了两个变量。

我有 whi 变量 account_idbuilding_id(最后根据 account_id 计算),在这种情况下,building_id 等于 account_id 并导致异常。

详细代码(控制器):

public function switchHeaders(Request $request) {

    $account = Account::find($request->get('account_id'));

    if ($request->has('account_id') && $account !== null) {

        session([
            'account_id'    => $account->id,
            'building_id'   => $account->building_id,
        ]);
    } else {
        session([
            'account_id'    => null,
            'building_id'   => null,
        ]);
    }

    return back();

谁能告诉我如何在这里找到问题

【问题讨论】:

    标签: php laravel session


    【解决方案1】:

    我认为您不需要在 if 条件中检查两个条件。只需像下面这样修改您的代码,看看它是否有效。

    public function switchHeaders(Request $request) {
    
        $account = Account::find($request->account_id);
    
        if (!empty($account)) {
    
            session([
                'account_id'    => $account->id,
                'building_id'   => $account->building_id,
            ]);
    
        } else {
            session([
                'account_id'    => null,
                'building_id'   => null,
            ]);
        }
    
        return back();
    

    【讨论】:

      【解决方案2】:

      您可以在这里使用optional 辅助方法:

      public function switchHeaders(Request $request) {
          $account = Account::find($request->get('account_id'));
      
          session([
              'account_id' => optional($account)->getKey(),
              'building_id' => optional($account)->getAttribute('building_id')
          ]);
      
          return back();
      }
      

      如果 $account 为 null,则可选帮助器从任何链式函数调用中返回 null。

      为了进一步减少控制器功能的逻辑,使用$account的可选参数设置路由:

      Route::get('switchHeaders/{account?}', 'AccountController@switchHeaders');
      

      并在RouteServiceProvider中显式绑定模型:

      Route::bind('account', function ($value) {
          return \App\Account::find($value);
      });
      

      这会将控制器功能减少到:

      public function switchHeaders(Request $request, $account = null) {
          session([
              'account_id' => optional($account)->getKey(),
              'building_id' => optional($account)->getAttribute('building_id')
          ]);
      
          return back();
      }
      

      不是将account_id 作为表单输入传递,而是作为表单操作的一部分:

      // i.e. http://example.com/switchHeaders/1
      <form action="switchHeaders/{{ $account->getKey() }}">
          ....
      </form>
      

      【讨论】:

      • 这并不能解决问题但是至于优化我发现了很多,因此谢谢!
      猜你喜欢
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 2014-09-12
      • 2012-03-04
      相关资源
      最近更新 更多