Laravel 7 API authentication for beginners
Tags: laravel, beginners, tutorial, webdev
Published: 2020-08-25 15:22:02

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,
],
```

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

```

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;
}
```

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');
```


and change the default middleware to sanctum
```
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
```


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;
    }

}
```


```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)
        ]);
    }
}
```

let's register a user using postman

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/96p44ww6bo5aeterxnkn.png)

and try to login
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/utg6avxr71zcw1mv95l1.png)

You are ready to go, cheers.