简体   繁体   中英

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

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

simply redirect the user when he access's the root for example you can add this to your web.php (or routes.php if version <= 5.2)

Route::get('/', function () {
 return redirect('dashboard');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM