User Authentication
On this page
Overview
In this guide, you can learn how to authenticate MongoDB users by using Laravel's native authentication functionality.
Laravel provides a native Auth
module that includes authentication services,
such as guards that define how users are authenticated and providers that define
how users are retrieved. To learn more about these services, see Authentication in the
Laravel documentation.
Modify the User Model
By default, Laravel generates the User
Eloquent model in your App/Models
directory. To enable authentication for MongoDB users, your User
model
must extend the MongoDB\Laravel\Auth\User
class.
To extend this class, navigate to your app/Models/User.php
file and replace the
use Illuminate\Foundation\Auth\User as Authenticatable
statement with the following
code:
use MongoDB\Laravel\Auth\User as Authenticatable;
Next, ensure that your User
class extends Authenticatable
, as shown in the following
code:
class User extends Authenticatable { ... }
After configuring your User
model, create a corresponding controller. To learn how to
create a controller, see the Create the User Controller section on this page.
Example
The following code shows a User.php
file that extends the MongoDB\Laravel\Auth\User
class:
namespace App\Models; use MongoDB\Laravel\Auth\User as Authenticatable; class User extends Authenticatable { protected $connection = 'mongodb'; protected $collection = 'users'; protected $fillable = [ 'name', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; }
Create the User Controller
To store functions that manage authentication, create an authentication controller for
your User
model.
Run the following command from your project root to create a controller:
php artisan make:controller <filename>
Example
The following command creates a controller file called AuthController.php
:
php artisan make:controller AuthController
The AuthController.php
file can store login()
and logout()
functions to
manage user authentication, as shown in the following code:
namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\ValidationException; use function response; class AuthController extends Controller { public function login(Request $request) { $request->validate([ 'email' => 'required|email', 'password' => 'required', ]); if (Auth::attempt($request->only('email', 'password'))) { return response()->json([ 'user' => Auth::user(), 'message' => 'Successfully logged in', ]); } throw ValidationException::withMessages([ 'email' => ['The provided credentials are incorrect.'], ]); } public function logout() { Auth::logout(); return response()->json(['message' => 'Successfully logged out']); } }
Customize User Authentication
You can customize your authentication files to align with your application's needs and enable additional authentication features.
This section describes how to use the following features to customize the MongoDB user authentication process:
Laravel Sanctum
Laravel Sanctum is an authentication package that can manage API requests and
single-page application authentication. To manage API requests, Sanctum issues
API tokens that are stored in the database and authenticates incoming HTTP
requests by using the Authorization
header. To authenticate single-page applications,
Sanctum uses Laravel's cookie-based authentication services.
You can install Laravel Sanctum to manage your application's authentication process. Run the following commands from your project root to install Laravel Sanctum and publish its migration file:
composer require laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
To use Laravel Sanctum with Laravel MongoDB, modify the PersonalAccessToken
model provided
by Sanctum to use the DocumentModel
trait from the MongoDB\Laravel\Eloquent
namespace.
The following code modifies the PersonalAccessToken
model to enable MongoDB:
namespace App\Models; use Laravel\Sanctum\PersonalAccessToken as SanctumToken; use MongoDB\Laravel\Eloquent\DocumentModel; class PersonalAccessToken extends SanctumToken { use DocumentModel; protected $connection = 'mongodb'; protected $collection = 'personal_access_tokens'; protected $primaryKey = '_id'; protected $keyType = 'string'; }
Next, run the following command to modify the database schema:
php artisan migrate
You can now instruct Sanctum to use the custom PersonalAccessToken
model by calling
the usePersonalAccessTokenModel()
method in one of your application's
service providers. To learn more, see Overriding Default Models
in the Laravel Sanctum guide.
Tip
To learn more about the DocumentModel
trait, see
Extend Third-Party Model Classes in the Eloquent Model Class guide.
Password Reminders
To add support for MongoDB-based password reminders, register the following service provider in your application:
MongoDB\Laravel\Auth\PasswordResetServiceProvider::class
This service provider modifies the internal DatabaseReminderRepository
to enable password reminders.
Example
The following code updates the providers.php
file in the bootstrap
directory
of a Laravel application to register the PasswordResetServiceProvider
provider:
return [ App\Providers\AppServiceProvider::class, MongoDB\Laravel\MongoDBServiceProvider::class, MongoDB\Laravel\Auth\PasswordResetServiceProvider::class ];
Additional Information
To learn more about user authentication, see Authentication in the Laravel documentation.
To learn more about Eloquent models, see the Eloquent Model Class guide.