Customising the AuthController in Laravel Spark

Whilst building up Get Hansel, I wanted to make it possible for people to sign up from the home page. This meant recreating the registration form which was easy enough, but when I sent an actual POST request to /register rather than an AJAX request, all the user saw was a blob of JSON. This wasn’t ideal, so I found where it needed to be fixed and submitted a pull request on Spark (you’ll need to be a Spark customer to see that).

Taylor declined the PR, explaining that if I want different behaviour, I should customise the AuthController. I couldn’t see any way to register my own auth controller as a service, so I added a new route that overwrote the one that Spark provided and implemented my custom functionality.

If you want to see the routes that Spark provides, look in vendor/laravel/spark/src/Http/routes.php. If you want to see the auth controller that Spark provides, look in vendor/laravel/spark/src/Http/Controllers/Auth/RegisterController.php.

To change the behaviour, I needed to add my own /register route to routes/web.php:

Route::post('/register', 'Auth\[email protected]');

Then, I had to create the controller that implemented my custom logic. Add the following to app/Http/Controllers/Auth/RegisterController.php:

<?php

namespace App\Http\Controllers\Auth;

use Laravel\Spark\Contracts\Http\Requests\Auth\RegisterRequest;
use Laravel\Spark\Http\Controllers\Auth\RegisterController as SparkRegisterController;

class RegisterController extends SparkRegisterController
{
    public function register(RegisterRequest $request) {
        $resp = parent::register($request);
        if ($request->wantsJson()) {
            return $resp;
        }
        return redirect($this->redirectPath());
    }
}

My class extends the Spark RegisterController and checks if the request wants JSON. If it does, it returns the original response. If not, we get redirected to the URL.

Once again I’m new to Laravel, but this is what worked for me. If there’s a better way to handle this, please do let me know

Michael is a polyglot software engineer, committed to reducing complexity in systems and making them more predictable. Working with a variety of languages and tools, he shares his technical expertise to audiences all around the world at user groups and conferences. You can follow @mheap on Twitter

Thoughts on this post

mariordev 2017-10-26

Thanks for sharing. This looks like a pretty good solution to me. However, don’t forget to also fire up the UserRegistered event.

Leave a comment?

Leave a Reply