DEV Community

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

Posted on • Edited on

2 2

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.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of PulumiUP 2025

From Cloud to Platforms: What Top Engineers Are Doing Differently

Hear insights from industry leaders about the current state and future of cloud and IaC, platform engineering, and security.

Save Your Spot

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay