skip to Main Content

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 AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use SrmklivePayPalServicePaypal;

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 AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;


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


  1. 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.

    Login or Signup to reply.
  2. Maybe you can be define middleware in the constructer of your controller

    public function __construct()
    {
        $this->middleware('auth:api');
    }
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search