Laravel Authentication (Auth) Tips and Tricks
Authentication is the process of identifying the user credentials. In web applications, authentication is managed by sessions which take the input parameters such as email or username and password, for user identification. If these parameters match, the user is said to be authenticated.
- Laravel’s
laravel/ui
package provides a quick way to scaffold all of the routes and views you need for authentication using a few simple commands:
composer require laravel/ui
php artisan ui vue --auth
- We log in with the user we choose from the table according to the id.
Login With Id Laravel (login by id)
//namespace
use Illuminate\Support\Facades\Auth;$user = User::find($user_id);Auth::login($user);
- Login and “remember” the given user…
Auth::login($user, true);
- You may specify the guard instance you would like to use:
Auth::guard('admin')->login($user);
- check current user is login or not:
Auth::check();
To manually log users out of your application, you may use the logout
method on the Auth
facade. This will clear the authentication information in the user's session:
Auth::logout();
Then, you may use the
logoutOtherDevices
method on theAuth
facade. This method requires the user to provide their current password, which your application should accept through an input form:
use Illuminate\Support\Facades\Auth;Auth::logoutOtherDevices($password);
- Get the currently authenticated user…
$user = Auth::user();
- Get the currently authenticated user’s ID…
$id = Auth::id();
“Attempt” we use for manually authenticating a user, this attempt method accepts an array of key/value pairs as its first argument. The values in the array will be used to find the user in your database table. this method will return true if authentication was successful. Otherwise, false will be returned.
if (Auth::attempt([‘active’ => 1])) {// The user is active, not suspended, and exists.}
If you are “remembering” users, you may use the
viaRemember
method to determine if the user was authenticated using the "remember me" cookie:
if (Auth::viaRemember()) {//}
If you are using PHP FastCGI, HTTP Basic authentication may not work correctly out of the box. The following lines should be added to your
.htaccess
file:
RewriteCond %{HTTP:Authorization} ^(.+)$RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]