Laravel自定义登录丢失重定向后的会话

时间:2018-11-14 13:36:30

标签: laravel

我需要双向登录。首先检查一个数据库是否存在用户,如果不存在则检查两个数据库。 所以我建立了一个自定义的登录控制器:

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Redirect;
use App\Http\Controllers\Controller;

class CustomLoginController extends Controller
{
    public function login(Request $request)
    {
    if($request->email) {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            // Authentication passed...
            return redirect()->intended('/');
        } else {
            DB::setDefaultConnection('otherdb');

            if (Auth::attempt($credentials)) {
                // The Login credentials will be found and user will be logged in 
but after Redirect to home user isn't logged in anymore.
                return redirect()->intended('/');
            } else {
                return redirect()->to('/login')
                    ->withInput($request->only($credentials['email'], 'remember'))
                    ->withErrors([
                        'email' => Lang::get('auth.failed'),
                    ]);
            }
        }
    } else {
        return view('auth.login');
    }
    }
}

在我使用“ DB :: setDefaultConnection('otherdb');”更改数据库连接后,第二次登录有效,但是在重定向到任何页面用户之后不再登录。 我究竟做错了什么? 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

Laravel尝试在每个请求中在数据库中查找用户。因此,重定向后,在默认数据库中没有用户 。数据库连接未存储在会话中。

我认为您需要使用

等其他用户模型创建自定义身份验证保护
class OtherUser extends Eloquent 
{
    protected $connection = 'otherdb';
}

并使用它。