Laravel会话不会被收集

I get stucked with following: I have switcher in my laravel application which request to Controller which actually does setting session parameters passed in form input and returns back() responce. Issue is that sometime it got filled incorrectly and mixing two variables.

I have whi variables account_id and building_id (last is calculated based on account_id) and in that case building_id becomes equal to account_id and leads to exception.

Code for detail (Controller):

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

Could anyone advise me how to find issue here

I think you don't need to check two conditions in if condition. just modify your code like below and see if it works.

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

You could use the optional helper method here:

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();
}

If $account in null, then the optional helper returns null from any chained function calls.

To further reduce the logic of the controller function, setup the route with an optional parameter for $account:

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

And explicitly bind the model in RouteServiceProvider:

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

Which would reduce the controller function to:

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

    return back();
}

Instead of passing in account_id as a form input, it would be part of the form's action:

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