Home > Net >  How to use Auth facade inside Controller with api route?
How to use Auth facade inside Controller with api route?

Time:09-13

I am accessing a PayPalController through routes in routes/api.php but when I try to check if a user is authenticated, it returns:

local.ERROR: Auth guard [api] is not defined.

PayPalController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Srmklive\PayPal\Service\Paypal;

class PayPalController extends Controller
{
    public function create(Request $request)
    {

        // both won't work
        $id = Auth::id('api');
        $id = auth('api')->user()->id;
        
    }
}

routes/api.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;


Route::post('/paypal/order/create', [PayPalController::class, 'create']);

CodePudding user response:

Check your config/auth.php and add an api guard to your app if you want to use the 'api' guard:

    'guards' => [
         ...
         'api' => [ 
             'driver' => 'session', 
             'provider' => 'users', 
         ],
     ],

Otherwise, just remove the 'api' and call it as auth(). By passing a parameter like 'api' you are telling laravel to use the api guard while it doesn't exist, and if you use only auth() it will use the default laravel guard (web) which I think is much better unless you really need to use another guard.

  • Related