REST-API in Laravel 8 using Laravel Passport and Authentication.
Introduction
I have the Analytics
Model Authenticable to authenticate the request in the web and api rather than using the default User
Model with corresponding analytics
and user
table.
I have created a login and register using this article. I was able to run the register
route and got the user in the analytics
table. However, I'm not able to access the login route.
Response
{
"message": "Invalid Credentials"
}
Request:
I'm sending POST
HTTP Request on endpoint http://example.com/api/login
and input the appropriate credentials
Below is the following configuration.
The Analytics
and User
Model are follow:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Notification;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Notifications\AnalyticsResetPassword;
use Illuminate\Database\Eloquent\Model;
class Analytics extends Authenticatable
{
use Notifiable, HasApiTokens;
public function sendPasswordResetNotification($token)
{
$this->notify(new AnalyticsResetPassword($token));
}
protected $table = "analytics";
protected $fillable = ['name', 'email', 'password', 'mobile', api_token', ];
protected $hidden = ['password', 'api_token', 'remember_token', ];
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['name', 'email', 'password', ];
protected $hidden = ['password', 'remember_token',];
protected $casts = ['email_verified_at' => 'datetime',];
}
App\Http\Controllers\Analytics\APIController
<?php
namespace App\Http\Controllers\Analytics;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Analytics;
class APIController extends Controller
{
public function login(Request $request)
{
$loginData = $request->validate([
'email' => 'email|required',
'password' => 'required'
]);
if (!auth()->attempt($loginData)) {
return response(['message' => 'Invalid Credentials']);
}
$accessToken = auth()->user()->createToken('authToken')->accessToken;
return response(['user' => auth()->user(), 'access_token' => $accessToken]);
}
}
I've tried modifying my config/auth.php
file like so:
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'analytics',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'analytics' => [
'driver' => 'eloquent',
'model' => App\Analytics::class,
],
],
];
EDIT1: I tried the following but no luck Laravel Passport Multiple Authentication using Guards