Laravel 6 JWT Multi-Model Authentication
If you are also messed up with JWT Multi-Model, then this article is for you.
In this article, I’m going to explain how, you can use any other model than Users to authenticate the APIs.
If you have Laravel 6 or above, install this specific version of jwt ^1.0.0
composer require tymon/jwt-auth ^1.0.0
Then, Add the service provider to the providers
array in the config/app.php
config file as follows:
'providers' => [
...
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]
Publish the config
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
Generate secret key
php artisan jwt:secret
This will update your .env
file with something like JWT_SECRET=foobar
Then uncomment the auth
middleware in the same file:
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
Update your User model
// Your custom model must extend Authenticatable and implementsJWTSubjectuse Illuminate\Foundation\Auth\User as Authenticatable;use Tymon\JWTAuth\Contracts\JWTSubject;
Configure Auth guard
Make a new guard for admin_api
Here we are making the admin_api guard to use the jwt
driver and admins provider.
We can now use Laravel’s built in Auth system, with jwt-auth doing the work behind the scenes!
Add some basic authentication routes
First let’s add some routes in routes/api.php
as follows:
AuthController
The whole magic is in this file.
Here, now you want to authenticate admins instead of users in this controller, so here you can set default driver to ‘admin’ in the construction function.
You can test your routes on postman.
If you also want to learn more about Laravel, You should learn about PHP namespace and traits and how they are used in Laravel.
I hope you learned in this article, I just wrote this article for you, please let me know, if this works for you. Thanks
Important Link: