Menu

REST with Laravel 5.4 – Part 2: Login & Logout

In this article, we will be looking into how to login and logout a user who is using token authentication to access your REST APIs. This is the second part of a series, you can read the first one here.

What are we trying to achieve?

Laravel generally expects an “api_token” in the “users” table, against which it compares the token sent by the user with each request (it can be in the header or in the url). And that is the extent till which the framework supports you in this case. How the api token gets to the user, is for the developer to the decide.

While integrating a back-end application with front-end frameworks like Angular or Backbone, I expect the following behavior –

The front-end sends a login request with the username (or email) and password.

The server authenticates the user and sends back a token if authentication succeeds.

The front-end uses the token for the subsequent requests to access the REST APIs.

The front-end sends a logout request.

The server invalidates the token.

Login: The Implementation

I have tried to use the AuthenticatesUsers trait and override the web login functionalities, but it is just too much work. So I prefer to just go ahead and create my own controller – Api\LoginController.php.

The “login” method will be quite simple. It will authenticate the user by the credential sent, create a fresh api token, save it in the database and send back the details in the response.

Exception Handling:

Let us now handle the usecases where the user sends wrong email/password. The client of course will be expecting the response in json format. To handle all the response I generally add a simple utility method in the base class (Controller.php) –