Laravel 5.5 API Tutorial: Part 2 – User Registration

This is Part 2 of multi-part walk-through of a Laravel 5.5. REST API example.  In Part 1 we covered how to install a fresh Laravel 5.5 project, and in this part we’ll move forward with creating a User Registration endpoint.  It’ll serve as a means to get user records into our API’s database, a prerequisite for later steps such as implementing JWT authentication.

Let’s get started.

Starting With A Default Migration

Before diving into adding user registration endpoint it’s worth running a default migration. Aside from introducing us as to Laravel’s migration mechanism, it’ll also add user related tables for us that’ll serve as a base for our user schema.

To run our first migration, run the following command from the project’s root:

php artisan migrate

After it completes, confirm that the database now has a users table.  It’ll be empty, but that’s ok, our user registration endpoint will provide means to get user records into the table.

Note: A password_resets table was also created, which can be ignored for now.

Creating the User Registration API

Now that we have a users table, we’re ready to create an API endpoint to write to it.  To start, first create the API route we’ll need for user registration.  Append the following to the routes/api.php file:

Route::group(['middleware' => ['api','cors']], function () {
    Route::post('auth/register', 'Auth\ApiRegisterController@create');
});

This will route to an ApiRegisterController we’ll create in a subsequent step.

Second, and in regard to the inclusion of cors in the route, since we’ll be making Cross Origin API requests, including with tools like Postman, Cross Origin request support is required.  To add the CORS package, run the following commands in the project’s root directory:

composer require barryvdh/laravel-cors
composer update
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

Then, add the following array element to the protected $routeMiddleware group in app/Http/Kernel.php:

'cors' => \Barryvdh\Cors\HandleCors::class

Third, create app/Http/Controllers/Auth/ApiRegisterController.php with the following contents:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

use Illuminate\Http\Request;

class ApiRegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    protected function create(Request $request)
    {
	return User::create([
	    'name' => $request->name,
	    'email' => $request->email,
	    'password' => bcrypt($request->password),
        ]);
    }
}

This is the ApiRegisterController that’ll handle our registration requests.  It’s worth noting that this is more or less a a copy of the default app/Http/Controllers/Auth/RegisterController, with two changes.  The first is the import of the Illuminate\Http\Request namespace in the file header, which allows the second change – this class’ create() method accepts a Request instance vs. an array.

Fourth, the registration endpoint is now ready to test. With Postman, and while the test server is running, send a test POST request to the following url: http://localhost:8000/auth/register.  Its body should include name, email, and password key/value parameters in a json string. Use whatever values you like for this test user, just remember them as we’ll use them in the next part of this walk through when we authenticate this test user.

Here’s what the request looks like in Postman:

Postman api request.

The request url and parameters in Postman. Note the JSON request body in the upper pane, and the response JSON in the lower pane.

Once the request is sent, verify the response contains the test user represented in JSON.  Also verify that a new record made it into the database.  If both of those are verified, the Registration API is complete! If you have any questions or hit any issues, feel free to leave a comment below and we can try to sort things out for you.

In the next post we’ll add a login method that also implements the beginnings of a JWT authentication model.

 

This entry was posted in General, Laravel, PHP. Bookmark the permalink.

One Response to Laravel 5.5 API Tutorial: Part 2 – User Registration

  1. su says:

    Nice! I wanted to implement Passport’s “Password grant tokens” while I realize I could not register user with api route. After following this article I can register user now, Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *