Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ilex01's avatar

Access auth() methods outside of Laravel

How do I access Auth::user()->id outside of the Laravel app?

0 likes
14 replies
martinbean's avatar

@ilex01 Why do you need to?

If you could get authenticated users’ ID outside of your Laravel app then so could any one else.

ilex01's avatar

I need to get the user_id of the users of a remote app in another app in jQuery:

// another app in jQuery
$.get('http://example.com/userid') // get the user id of the user registered on the app, example.com
  .done(function(response) {
    console.log(response); // get user id
  });
ilex01's avatar

@martinbean Thanks for trying to help. For me, It doens't matter that anyone else could get the user id, I just want to get it, as I can.

martinbean's avatar

@ilex01 Then what’s the problem? Just return the authenticate user’s ID from that super insecure endpoint you’re calling via jQuery like it’s 2013?

class SomeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function userid(Request $request)
    {
        return response($request->user()->getKey());
    }
}
ilex01's avatar

@martinbean Even if i'm logged in, I get the login.blade.php as a result in my jQuery app.

Snapey's avatar

@ilex01 you run this http route

$.get('http://example.com/userid')

How in earth does the server know WHICH user you are talking about?

1 like
martinbean's avatar

@ilex01 But why are you trying to randomly get a user ID via AJAX in the first place?

martinbean's avatar

@ilex01 Why not just build an API endpoint that returns the data you actually want? 🤷‍♂️

1 like
JaylonFranecki's avatar

Before using any Laravel-specific functionality, you need to bootstrap the Laravel application. This involves initializing the Laravel framework and its components.

$app = require_once '/path/to/your/laravel/app/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

Please or to participate in this conversation.