Customising the AuthController in Laravel Spark

12 Jan 2017 in Tech

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:

php
Route::post('/register', 'Auth\RegisterController@register');

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

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