{"flag":true,"single":true,"pageTitle":"Laravel Login authentication system default methods, AuthenticatesUsers trait for login, RegistersUsers Trait for register","post":{"id":258,"user_id":"1","slug":"laravel-login-authentication-system-default-methods-authenticatesusers-trait-for-login-registersusers-trait-for-register-tn0u","title":"Laravel Login authentication system default methods, AuthenticatesUsers trait for login, RegistersUsers Trait for register","body":"<p>You can access these methods in LoginControllers:<\/p>\r\n<p>The AuthenticatesUsers trait, which is part of Laravel's default authentication system, includes several methods that handle the logic around user authentication, login attempts, redirects, and more.<\/p>\r\n<p>1. <em><strong>Credientials<\/strong><\/em> Method to check if <strong>status <\/strong>colum has value <strong>active<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>use Illuminate\\Http\\Request; \r\nprotected function credentials(Request $request)\r\n    {\r\n        \/\/ Include status check along with email and password\r\n        return array_merge($request-&gt;only($this-&gt;username(), 'password'), ['status' =&gt; 'active']);\r\n    }<\/code><\/pre>\r\n<p>&nbsp;<\/p>\r\n<p>2. OR Override the <strong>attemptLogin<\/strong> Method&nbsp;<\/p>\r\n<pre class=\"language-markup\"><code>use Illuminate\\Http\\Request;\r\nprotected function attemptLogin(Request $request)\r\n    {\r\n        \/\/ First, get the user by their email\r\n        $user = \\App\\Models\\User::where($this-&gt;username(), $request-&gt;email)-&gt;first();\r\n\r\n        \/\/ Check if the user exists and if their status is 'non_active'\r\n        if ($user &amp;&amp; $user-&gt;status === 'non_active') {\r\n            \/\/ If the user's status is non_active, redirect them with an error\r\n            return redirect()-&gt;back()-&gt;withErrors(['email' =&gt; 'Your account is not active.']);\r\n        }\r\n\r\n        \/\/ If the user is active, attempt login\r\n        return $this-&gt;guard()-&gt;attempt(\r\n            $this-&gt;credentials($request),\r\n            $request-&gt;filled('remember')\r\n        );\r\n    }<\/code><\/pre>\r\n<p>&nbsp;<\/p>\r\n<p>3. <strong>sendFailedLoginResponse&nbsp;<\/strong>if user is not authenticated, return responce also<\/p>\r\n<pre class=\"language-markup\"><code>\/**\r\n     * Send the response after the user's login attempt fails.\r\n     *\r\n     * @param  \\Illuminate\\Http\\Request  $request\r\n     * @return \\Illuminate\\Http\\Response\r\n     *\r\n     * @throws \\Illuminate\\Validation\\ValidationException\r\n     *\/\r\n   protected function credentials(Request $request)\r\n    {\r\n        return array_merge($request-&gt;only($this-&gt;username(), 'password'), ['status' =&gt; 'active']);\r\n    }\r\n    protected function sendFailedLoginResponse(Request $request)\r\n    {\r\n        $user = \\App\\Models\\User::where($this-&gt;username(), $request-&gt;email)-&gt;first();\r\n\r\n        if ($user &amp;&amp; $user-&gt;status === 'non_active') {\r\n            \/\/ If the user is non_active, show this custom error\r\n            throw ValidationException::withMessages([\r\n                $this-&gt;username() =&gt; ['Your account is not active.'],\r\n            ]);\r\n        }\r\n\r\n        \/\/ For other cases, use the default error\r\n        throw ValidationException::withMessages([\r\n            $this-&gt;username() =&gt; [trans('auth.failed')],\r\n        ]);\r\n    }<\/code><\/pre>\r\n<p>4. <strong>showLoginForm <\/strong>: Displays the login form to the user.<\/p>\r\n<pre class=\"language-markup\"><code>public function showLoginForm()\r\n{\r\n    return view('auth.login');\r\n}\r\n<\/code><\/pre>\r\n<p>5. <strong>LOGIN<\/strong> METHOD: Handles the login request, processes the credentials, and attempts to authenticate the user.<\/p>\r\n<pre class=\"language-markup\"><code>public function login(Request $request)\r\n{\r\n    $this-&gt;validateLogin($request);\r\n\r\n    if (method_exists($this, 'hasTooManyLoginAttempts') &amp;&amp;\r\n        $this-&gt;hasTooManyLoginAttempts($request)) {\r\n        $this-&gt;fireLockoutEvent($request);\r\n\r\n        return $this-&gt;sendLockoutResponse($request);\r\n    }\r\n\r\n    if ($this-&gt;attemptLogin($request)) {\r\n        return $this-&gt;sendLoginResponse($request);\r\n    }\r\n\r\n    $this-&gt;incrementLoginAttempts($request);\r\n\r\n    return $this-&gt;sendFailedLoginResponse($request);\r\n}\r\n<\/code><\/pre>\r\n<p>&nbsp;<\/p>\r\n<p>6. <strong>sendLoginResponse: <\/strong>Handles the response after a successful login.<strong><br><\/strong><\/p>\r\n<pre class=\"language-markup\"><code>protected function sendLoginResponse(Request $request)\r\n{\r\n    $request-&gt;session()-&gt;regenerate();\r\n\r\n    $this-&gt;clearLoginAttempts($request);\r\n\r\n    return $this-&gt;authenticated($request, $this-&gt;guard()-&gt;user())\r\n            ?: redirect()-&gt;intended($this-&gt;redirectPath());\r\n}\r\n<\/code><\/pre>\r\n<p>7. Logout<\/p>\r\n<pre class=\"language-markup\"><code>public function logout(Request $request)\r\n{\r\n    $this-&gt;guard()-&gt;logout();\r\n\r\n    $request-&gt;session()-&gt;invalidate();\r\n\r\n    $request-&gt;session()-&gt;regenerateToken();\r\n\r\n    return redirect('\/');\r\n}\r\n<\/code><\/pre>\r\n<p>8. redirectPath<\/p>\r\n<pre class=\"language-markup\"><code>protected function redirectPath()\r\n{\r\n    return '\/home';\r\n}\r\n<\/code><\/pre>\r\n<p>9.&nbsp;<\/p>\r\n<p>&nbsp;<\/p>\r\n<p><strong><span style=\"font-size: 18pt;\">RegistersUsers Trait<\/span><\/strong><\/p>\r\n<p><span style=\"font-size: 12pt;\"><strong>1.showRegistrationForm<br><\/strong><\/span><\/p>\r\n<pre class=\"language-markup\"><code>public function showRegistrationForm()\r\n{\r\n    return view('auth.register');\r\n}\r\n<\/code><\/pre>\r\n<p>2. &nbsp;Handles the registration request, validates the input, and creates a new user. &nbsp;<br><strong>Default behavior:<\/strong> Validates the form input, creates the user, logs them in, and redirects to the intended page.<\/p>\r\n<pre class=\"language-markup\"><code>public function register(Request $request)\r\n{\r\n    $this-&gt;validator($request-&gt;all())-&gt;validate();\r\n\r\n    event(new Registered($user = $this-&gt;create($request-&gt;all())));\r\n\r\n    $this-&gt;guard()-&gt;login($user);\r\n\r\n    return $this-&gt;registered($request, $user)\r\n                    ?: redirect($this-&gt;redirectPath());\r\n}\r\n<\/code><\/pre>\r\n<p><span style=\"font-size: 12pt;\"><strong>3. validator: <\/strong>Validates the registration form data.<\/span><\/p>\r\n<pre class=\"language-markup\"><code>protected function validator(array $data)\r\n{\r\n    return Validator::make($data, [\r\n        'name' =&gt; ['required', 'string', 'max:255'],\r\n        'email' =&gt; ['required', 'string', 'email', 'max:255', 'unique:users'],\r\n        'password' =&gt; ['required', 'string', 'min:8', 'confirmed'],\r\n    ]);\r\n}\r\n<\/code><\/pre>\r\n<p>4. create<\/p>\r\n<pre class=\"language-markup\"><code>protected function create(array $data)\r\n{\r\n    return User::create([\r\n        'name' =&gt; $data['name'],\r\n        'email' =&gt; $data['email'],\r\n        'password' =&gt; Hash::make($data['password']),\r\n    ]);\r\n}\r\n<\/code><\/pre>\r\n<p>5. &nbsp;Handles additional logic after the user is registered (optional).<\/p>\r\n<pre class=\"language-markup\"><code>protected function registered(Request $request, $user)\r\n{\r\n    \/\/\r\n}\r\n<\/code><\/pre>\r\n<p>&nbsp;<\/p>\r\n<p>&nbsp;<\/p>\r\n<p>EXAMPLE:<\/p>\r\n<pre class=\"language-markup\"><code>namespace App\\Http\\Controllers\\Auth;\r\n\r\nuse App\\Http\\Controllers\\Controller;\r\nuse App\\Models\\User;\r\nuse Illuminate\\Support\\Facades\\Hash;\r\nuse Illuminate\\Support\\Facades\\Validator;\r\nuse Illuminate\\Foundation\\Auth\\RegistersUsers;\r\n\r\nclass RegisterController extends Controller\r\n{\r\n    use RegistersUsers;\r\n\r\n    \/**\r\n     * Where to redirect users after registration.\r\n     *\r\n     * @var string\r\n     *\/\r\n    protected $redirectTo = '\/home';\r\n\r\n    \/**\r\n     * Create a new controller instance.\r\n     *\r\n     * @return void\r\n     *\/\r\n    public function __construct()\r\n    {\r\n        $this-&gt;middleware('guest');\r\n    }\r\n\r\n    \/**\r\n     * Get a validator for an incoming registration request.\r\n     *\r\n     * @param  array  $data\r\n     * @return \\Illuminate\\Contracts\\Validation\\Validator\r\n     *\/\r\n    protected function validator(array $data)\r\n    {\r\n        return Validator::make($data, [\r\n            'name' =&gt; ['required', 'string', 'max:255'],\r\n            'email' =&gt; ['required', 'string', 'email', 'max:255', 'unique:users'],\r\n            'password' =&gt; ['required', 'string', 'min:8', 'confirmed'],\r\n        ]);\r\n    }\r\n\r\n    \/**\r\n     * Create a new user instance after a valid registration.\r\n     *\r\n     * @param  array  $data\r\n     * @return \\App\\Models\\User\r\n     *\/\r\n    protected function create(array $data)\r\n    {\r\n        return User::create([\r\n            'name' =&gt; $data['name'],\r\n            'email' =&gt; $data['email'],\r\n            'password' =&gt; Hash::make($data['password']),\r\n        ]);\r\n    }\r\n}\r\n<\/code><\/pre>\r\n<p>&nbsp;<\/p>\r\n<p>&nbsp;<\/p>\r\n<p>&nbsp;<\/p>","category_id":"2","is_private":"0","created_at":"2024-10-24T06:52:52.000000Z","updated_at":"2024-10-24T06:52:52.000000Z","category":{"id":2,"user_id":"1","name":"Laravel Core","slug":"laravel-nhyt","parent_id":"1","created_at":"2023-03-14T03:58:27.000000Z","updated_at":"2023-03-20T11:30:50.000000Z"},"user":{"id":1,"name":"R GONDAL","email":"rizikmw@gmail.com","email_verified_at":null,"two_factor_confirmed_at":null,"current_team_id":"1","profile_photo_path":null,"created_at":"2023-03-12T10:49:33.000000Z","updated_at":"2025-01-10T12:59:00.000000Z","profile_photo_url":"https:\/\/ui-avatars.com\/api\/?name=R+G&color=7F9CF5&background=EBF4FF"}},"pageDesc":"You can access these methods in LoginControllers: The AuthenticatesUsers trait, which is part of Laravel's default authentication system, in - Laravel Login authentication system default methods, AuthenticatesUsers trait for login, RegistersUsers Trait for register (Updated: October 24, 2024) - Read more about Laravel Login authentication system default methods, AuthenticatesUsers trait for login, RegistersUsers Trait for register at my programming site [SITE]","categories":[]}