Search code examples
phplaravelurlhttp-redirectprogram-entry-point

Laravel redirect login, main URL


I have the Laravel auth system configured and it works. When a user logs in, he is redirected to his dashboard. But when it closes the page or revises the main URL www.xyz.com, it is not redirected to the dashboard. How can I redirect the user to his dashboard when he is logged in and he visit the main URL?

LoginController.php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/iboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => ['logout', 'userLogout']]);
    }

    /**
    * Get the needed authorization credentials from the request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return array
    */
   protected function credentials(Request $request)
   {
       $field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL)
           ? $this->username()
           : 'username';

       return [
           $field => $request->get($this->username()),
           'password' => $request->password,
       ];
   }

    public function userLogout()
    {
        Auth::guard('web')->logout();
        return redirect('/logout');
    }
}

Solution

  • Heres a simple solution, when a user visits the page www.xyz.com you can check if the user is logged in by using

    use Illuminate\Support\Facades\Auth;
    if (Auth::check()) {
     //Executes when user is logged in
      return redirect('dashboard');
    }
    

    The above code checks if a user is logged in if he is then he gets redirected else he won't get redirected and still be on www.xyz.com.

    Hopefully, this answer helps.

    Here are some cool some cool stuff you can do with laravel auth:- https://laravel.com/docs/5.5/authentication