Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

scala's avatar
Level 1

authenticate user and store username in session

I have implemented user authentication using library packages, I do not know what I have used, I just followed the tutorial.

Now I have to extend this authentication module.

  1. if someone try to browse any pages via url without doing authenticate login, he/she should be redirected to the login page.

  2. store the authenticated user in session and displays the username in other pages.

login controller code

namespace App\Http\Controllers\Auth;

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

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 = '/book';

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

route code block

Auth::routes();
0 likes
1 reply
munazzil's avatar
munazzil
Best Answer
Level 13

@SCALA

use book instead home in protected $redirectTo.

namespace App\Http\Controllers\Auth;

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

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 = '/home'; <- Use like this.

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

}

Please or to participate in this conversation.