Auth facade returns null if called from Controller with api route

Viewed 41

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

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)
    {

        // returns null
        $id = Auth::id();

        // can't read "id" of null
        $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']);

I've tried creating an api guard in config/auth.php and using it like so:

auth('api')->user()->id

but it changes nothing.

Edit:

A user is authenticated and it still returns null.

3 Answers

It returns null, because no user is authenticated yet. If you want to check for user authentication, you can just use it like:

If(Auth::check()){
    //Your code here
}

Or vice versa.

Maybe you can be define middleware in the constructer of your controller

public function __construct()
{
    $this->middleware('auth:api');
}

=>your route will be add on middleware.

Route::group(['middleware' => 'auth:api'] ,function () {

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

});

=>auth will be check this is login ya not and pass your login.if you check your api then pass the bearer token then run the api and access your $id = Auth::id(); auth id.
Related