Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use Auth facade inside Controller with api route?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?php

namespace App\Http\Controllers;

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


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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading