jeudi 2 avril 2020

Laravel 5.4 with custom login failed to redirect

I am facing problem with the login with laravel 5.4 where after successful login user will still redirect to login page. I have referred to different materials The documentation, custom guard , custom login, Multiple Guard but I couldnt get the solution on this. I have also tried to dd($guard) in RedirectIfAuthenticated but returns null. How to redirect and keep users remain at home page after login?

Web.php

Route::get('/', 'HomeController@index');

// Authentication routes...
Route::get('auth/login', 'Auth\LoginController@getLogin')->name('login');
Route::post('auth/login', 'Auth\LoginController@postLogin');
Route::get('auth/logout', 'Auth\LoginController@getLogout')->name('logout');

// Registration routes...
Route::get('auth/register', 'Auth\RegisterController@getRegister')->name('register');
Route::post('auth/register', 'Auth\RegisterController@postRegister');

// Password reset link request routes...
Route::get('password/email', 'Auth\PasswordController@getEmail');
Route::post('password/email', 'Auth\PasswordController@postEmail');

// Password reset routes...
Route::get('password/reset/{token}', 'Auth\PasswordController@getReset');
Route::post('password/reset', 'Auth\PasswordController@postReset');

Login Controller

use AuthenticatesUsers;

    protected $redirectTo = '/home';
    protected $redirectAfterLogout = '/auth/login';

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

     protected function guard()
    {
        return Auth::guard('users');
    }

    protected function authenticated(Request $request, $user)
    {
        return redirect('/home');
    }

    public function getLogin()
    {
            return view('auth.login');
    }

    public function postLogin(Request $request)
    {
        $this->validate($request, [
            'username' => 'required',
            'password' => 'required|min:6',
        ]);

        $credentials = array(
                'username' => $request->input('username'),
                'password' => $request->input('password'),
        );

        $userData = User::where('username',$request->username)->first();

        if (auth()->attempt($credentials, $request->has('remember')))
        {
                return redirect($this->redirectTo);
        }

        return redirect()->back()
                    ->withInput($request->only('username', 'remember'))
                    ->withErrors([
                        'username' => 'This credentials do not match our records.',
                    ]);
    }

I have also tried to change the return after success login to return view('home'), able to redirect to the home page but it wont keep the user logged in.

if (auth()->attempt($credentials, $request->has('remember')))
        {
                return view('home'); // The changes made
        }


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire