John Davidson

php - Auth facade returns null if called from Controller with api route

0 comments
Message:


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.



My Answer:
php
namespace App\Http\Controllers;

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

class PayPalController extends Controller
{
public function processPayment(Request $request)
{
if (Auth::check()) {
// User is authenticated
return response()->json(['message' => 'User is authenticated']);
} else {
// User is not authenticated
return response()->json(['message' => 'User is not authenticated']);
}
}
}


In order to access the Auth facade in a controller, make sure that the controller extends the `Controller` class provided by Laravel. Also, ensure that you are using the correct namespace for the `Auth` facade. If you are still facing issues with the Auth facade returning null, you may need to check your authentication setup and configuration in your Laravel application.

Rate this post

3 of 5 based on 4837 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us