Simple custom login and register REST API in Laravel 7

Laravel is the MVC framework of PHP. Most of the PHP developer work on Laravel so do I. In my earlier post I have created How to create REST API in PHP but why bother to start from scratch if everything is ready for use in Laravel. So let’s see simple custom login and register REST API in Laravel 7. I will add Github repo in the end of the article.

I am assuming you have a setup of laravel project if not then I recommend following this How to install and setup Laravel article first. In this article, I am not going to use Lumen its regular laravel Project. I will create another article for Lumen.

Initiate a new project with Composer

Open terminal or cmd and type the following command and this will create a project folder with laravel directories.

composer create-project --prefer-dist laravel/laravel yourProjectName

Add auth scaffolding

We will be using the Auth scaffolding of laravel.

In older version laravel was using below command to install auth scaffolding. Now it is obsolete and won’t work.

php artisan make:auth

Laravel 7, for Auth scaffolding uses following two commands.

composer require laravel/ui
php artisan ui vue --auth

and if you need UI of auth login and register use the following command.

npm install && npm run dev

Database setup

Now create a database in your MySQL server or PHPMyAdmin and add database name in .env file.

Replace with your credentials.

Auth scaffolding have already users Controller, Migration, Model ready to use, It has already columns like name, email, password, etc.. If you want to add more columns you can add. This migration file is located at database/migartions/date_create_users_table.php

Now run the following command to add users table in database.

php artisan migrate

Create a resource file

When you build a API in Laravel your model needs to be transformed into JSON, because your end application expects JSON data. To transfrom your all model data JSON laravel has Resource classes. Lets see how it works. Type the following commad to create a Resource.

php artisan make:resource UserResource

A new file named UserResource.php will be created in app/Http/Resources directory. Now open edit UserResource.php

  public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }

yes , you can add or remove any columns you want. The same array of data will be returned when you call the login or register API.

Create a controller

Now lets create a Controller file to add logic part of login and register. To create a controller type the following command.

php artisan make:controller ApiController

This will create ApiController.php in app/Http/Controller, Add two functions login and register with the following code in ApiController.php then file will look like this.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\User;
use App\Http\Resources\UserResource;

class ApiController extends Controller
{
    //
    public function login(Request $request)
    {
        $user = User::where('email', $request->email)->first();
        if (!empty($user)) {
            if (!Hash::check($request->password, $user->password)) {
                return response()->json(['success' => false, 'message' => 'Login Fail, pls check password']);
            }
            return new UserResource($user);
        } else {
            return json_encode(['error' => 'Login Fail, pls check  email']);
        }
    }
    public function register(Request $request)
    {
        $user = new User;
        $user->email = $request->email;
        $user->name = $request->name;
        $user->password = Hash::make($request->password);
        $user->save();
        return new UserResource($user);
    }
}

As you can see in both function we are returning UserResource() by passing user model instance.

Create routes

Its time to create routes for login and register. To create route open routes/api.php and add the following code.

Route::post('login', 'ApiController@login');
Route::post('register', 'ApiController@register');

This will open up two routes or say API with POST request. So to call these routes we need to start the server. Run the following command to run the server

php artisan serve

Well, this command will start your server at http://127.0.0.1:8000

To test our created routes/API we gonna need POSTMAN or similar tool. Let me add some screenshot of these two routes.

Simple custom login and register REST API in Laravel 7
http://127.0.0.1:8000/api/register
Simple custom login and register REST API in Laravel 7
http://127.0.0.1:8000/api/login

Do not wonder if you see api in URL http://127.0.0.1:8000/api/login, it’s because it is by the Laravel default feature.

Here is the Github link of this article.

So that is all about simple custom login and register REST API in Laravel 7. If you have any question or doubt leave the comment in the below comment box.

See also

Leave a Reply

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