Home > OS >  Auth facade returns null if called from Controller with api route
Auth facade returns null if called from 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 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.

CodePudding user response:

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.

CodePudding user response:

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

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

  • Related