Dumbing down

I’ve reached a point in my Laravel for Frontend developers screencast series where I need to authenticate a user in order to write the other endpoints of the API I’m building as an example application.

The latest and best authentication solution for SPAs with Laravel as a backend is Sanctum, so I started recording a lesson explaining what it does and how it works. But no matter how much I tried to dumb it down, it still felt too complicated for the regular frontend developer who is just getting started with Laravel.

Instead of possibly putting people off by introducing a somewhat complicated-to-setup Sanctum, I decided to figure out a way to have an authenticated user without actually building the authentication part.

Luckily, in Laravel, we can authenticate any user by calling Auth::login($user).

The only thing I had to do is to find a proper place to call it.

The first idea was to create a middleware and apply it to all the routes requiring an authenticated user. But that would have meant creating a new middleware class and registering it in the app/Http/Kernel.php file, only to remove it later in the series.

Then I thought, instead of creating and registering a whole new middleware class, I could just write it as a closure.

    'middleware' => function ($request, Closure $next) {
        $user = User::first();
        return $next($request);
], function () {
    // routes

But even so, I’m avoiding Sanctum by introducing a new concept that I have to explain: Middlewares.

Middlewares are far easier to explain than Sanctum, but is there any way to simplify this even further?

Yes, there is. I present you the OG middleware:

// routes/api.php
$user = User::first();

// route list goes here

We authenticate the user just before defining our application routes. We avoid Sanctum and middlewares by doing something pretty much everybody would be able to quickly understand: before we hit the routes, we log in the first user we can find, using the Auth facade.

I learned everything I know by watching and reading tutorials. As I became more experienced, I slowly became disappointed in authors for not showing me the cooler or the better way of doing things.

Now that I’m trying my hand on screencasts, I can *TOTALLY* see why they were doing that and how hard it is to be mindful and simplify everything so you won’t overwhelm the person watching your content and trying to make sense of it.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.