Laravel Sanctum Install and Login and Register

Created At: 2023-04-27 01:40:03 Updated At: 2023-04-27 02:12:57

Here we will see how to install Laravel Sanctum package and use it for authentication of our users registration and login.

It's used for mobile applications with simple and token based APIs. It provides software developers with a safe and reliable way to authenticate users and manage authorization for their applications.

It's super secured sinces it's token based and the token is saved in the server. Let's go ahead and see how to install and use sanctum.

Let's go ahead and install sanctum. Make sure you have a laravel application installed on your machine. Let's install it via composer

composer require laravel/sanctum

This will install it and then we neeed to publish it.

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

it will publish the package and now let's migrate. 

php artisan migrate

Once sanctum installed, published and migrated, you are ready to use it. It''s already available to use for User model table.

Your User model class will have HasApiTokens class which will help to use User table and do authentication. 

Now let's create a controller using below command

php artisan make:controller Api\\UserController

With the above command we will have a new controller class named UserController inside app\Htt\Controllers\Api folder.

Let's put the below code in the UserController.php class 

<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    /**
     * Create User
     * @param Request $request
     * @return User 
     */
    public function createUser(Request $request)
    {
        try {
            //Validated
            $validateUser = Validator::make($request->all(), 
            [
                'name' => 'required',
                'email' => 'required|email|unique:users,email',
                'password' => 'required'
            ]);

            if($validateUser->fails()){
                return response()->json([
                    'status' => false,
                    'message' => 'validation error',
                    'errors' => $validateUser->errors()
                ], 401);
            }

            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password)
            ]);

            return response()->json([
                'status' => true,
                'message' => 'User Created Successfully',
                'token' => $user->createToken("API TOKEN")->plainTextToken
            ], 200);

        } catch (\Throwable $th) {
            return response()->json([
                'status' => false,
                'message' => $th->getMessage()
            ], 500);
        }
    }

    /**
     * Login The User
     * @param Request $request
     * @return User
     */
    public function loginUser(Request $request)
    {
        try {
            $validateUser = Validator::make($request->all(), 
            [
                'email' => 'required|email',
                'password' => 'required'
            ]);

            if($validateUser->fails()){
                return response()->json([
                    'status' => false,
                    'message' => 'validation error',
                    'errors' => $validateUser->errors()
                ], 401);
            }

            if(!Auth::attempt($request->only(['email', 'password']))){
                return response()->json([
                    'status' => false,
                    'message' => 'Email & Password does not match with our record.',
                ], 401);
            }

            $user = User::where('email', $request->email)->first();

            return response()->json([
                'status' => true,
                'message' => 'User Logged In Successfully',
                'token' => $user->createToken("API TOKEN")->plainTextToken
            ], 200);

        } catch (\Throwable $th) {
            return response()->json([
                'status' => false,
                'message' => $th->getMessage()
            ], 500);
        }
    }
}

Here we defined two methods createUser and loginUser

createUser method validates, during validation it looks for the users table and see if the email is unique or not. If the email address is unique it's created and returned as new user with token. The token is returned as plain text token so that human can read that.

We need to register the APIs we created in api.php file

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\AuthController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/

Route::post('/auth/register', [UserController::class, 'createUser']);
Route::post('/auth/login', [UserController::class, 'loginUser']);

Comment

  • b
    biniyam yoseph

    2024-04-13 17:26:10

    nice

Add Reviews