Matt Kingshott

Web software developer

Add a global authenticated user helper

I'm always looking for ways to reduce the amount of code that I have to write within my Laravel applications.

To that end, I always make a point of adding the following function to my global helpers file:

use App\Models\User;

/**
 * Retrieve the currently authenticated user.
 *
 */
function user() : ?User
{
    return auth()->user();
}

While only saving a few keystrokes, this does add up over time.

As a bonus, the return type is hinted to User instead of a generic authenticated class (so IDE support is better).

© 2024 Matt Kingshott.