DEV Community

Cover image for Laravel 7 API authentication for beginners
Apu Chakraborty
Apu Chakraborty

Posted on • Updated on

Laravel 7 API authentication for beginners

Nowadays, API is becoming the most essentials for modern applications. In this article, we will see how can we create APIs using Laravel 7 easily.
We are not going to cover what API is and why we should use it. So if you don't know What API is? then google it first and then come here.

Let's come to the Point

First of all, let's create a fresh Laravel project

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

We are going to use Laravel sanctum to get token so, let's install sanctum

composer require laravel/sanctum

Now publish the configuration files and migrations

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

Now, it's time to add EnsureFrontendRequestsAreStateful middleware to your API middleware group in your app/Http/Kernel.php file

use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Enter fullscreen mode Exit fullscreen mode

Configure your database in .env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=yourdatabasename
DB_USERNAME=username
DB_PASSWORD=password

Enter fullscreen mode Exit fullscreen mode

let's migrate

php artisan migrate

it is responsible for creating the user table in your application.

Next, go to User Model in App/User.php and add this code

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}
Enter fullscreen mode Exit fullscreen mode

Next, go to the routes folder and open api.php
and add this line of routes

Route::post('/register', 'RegisterController@register');
Route::post('/login', 'LoginController@login');
Enter fullscreen mode Exit fullscreen mode

and change the default middleware to sanctum

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
Enter fullscreen mode Exit fullscreen mode

Now create two controller RegisterController and LoginController

php artisan make:controller LoginController

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

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

        if (!$user || !Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }

        return $user->createToken('x-key')->plainTextToken;
    }

}
Enter fullscreen mode Exit fullscreen mode

php artisan make:controller RegisterController

<?php

namespace App\Http\Controllers;

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

class RegisterController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'name' => ['required'],
            'email' => ['required', 'email', 'unique:users'],
            'password' => ['required', 'min:8', 'confirmed']
        ]);

        User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password)
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

let's register a user using postman

Alt Text

and try to login
Alt Text

You are ready to go, cheers.

Discussion (0)