I am getting the error InvalidArgumentException: Auth guard [auth] is not defined. with the below given code.I understood this error is because I have added auth in the guards array of config/sanctum.php . But I am not understanding what else is to be given there instead of auth.
My actual requirement is to get the logged in user's id in my API by using the sanctum middleware for authentication. It currently returns null for the line of code in controller.
Does anyone know what all fixes shall i make in this context? Any help is appreciated.
Controller
dd(auth()->user());
routes/api.php
Route::post('login', [UserController::class, 'Login'])->name('login');
Route::group(['prefix' => 'user'],function () {
Route::group(['middleware' => ['user','auth:sanctum']], function () {
Route::post('send-msg', [ChatController::class, 'store'])->name('send-msg');
});
}
);
Kernal.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'user' => \App\Http\Middleware\AuthUser::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
config/sanctum.php
'guard' => ['web','auth'],
config/auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'sanctum',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
],
Http/Middleware/Authenticate.php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
auth() is belong to laravel web authentication which maintains state using session storage and cookies, not sanctum it self. what authentication method your app is using?
you should just use laravel web authentication if you are developing laravel web.
Your User Model should you HasApi Trait
Then to guard your route