# Sanctum Authentication

This guide shows how to create an API with Laravel Sanctum. You will need to adjust the final output to fit our model. You can view the expected response from different perspectives using the following tools:

### Create Controller <a href="#step-2-create-controller" id="step-2-create-controller"></a>

Create new controller in `Http/Controllers/AuthController.php` by the following command:

```yang
php artisan make:controller AuthController
```

then, add routes for api in `api.php` file and include AuthController

### Create Route <a href="#step-1-create-route" id="step-1-create-route"></a>

Open `api.php` from routes folder and replace the code of route with the following:

<pre class="language-dataweave"><code class="lang-dataweave">&#x3C;?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
<strong>use App\Http\Controllers\AuthController;
</strong>/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

<strong>Route::group(['prefix' => 'auth'], function () {
</strong><strong>    Route::post('login', [AuthController::class, 'login']);
</strong><strong>    Route::post('register', [AuthController::class, 'register']);
</strong><strong>
</strong><strong>    Route::group(['middleware' => 'auth:sanctum'], function() {
</strong><strong>      Route::get('logout', [AuthController::class, 'logout']);
</strong><strong>      Route::get('user', [AuthController::class, 'user']);
</strong><strong>    });
</strong><strong>});
</strong></code></pre>

{% hint style="info" %}
We will create APIs and to test those APIs on [POSTMAN](https://www.postman.com/downloads/).
{% endhint %}

### Register User API <a href="#step-3-register-user-api" id="step-3-register-user-api"></a>

Open `Http/Controllers/AuthController.php` and replace below code:

<pre class="language-php"><code class="lang-php">&#x3C;?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
<strong>use App\Models\User;
</strong>use Validator;

class AuthController extends Controller
{
    /**
    * Create user
    *
    * @param  [string] name
    * @param  [string] email
    * @param  [string] password
    * @param  [string] password_confirmation
    * @return [string] message
    */
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'email'=>'required|string|unique:users',
            'password'=>'required|string',
            'c_password' => 'required|same:password'
        ]);

        $user = new User([
            'name'  => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ]);

        if($user->save()){
            $tokenResult = $user->createToken('Personal Access Token');
            $token = $tokenResult->plainTextToken;

            return response()->json([
            'message' => 'Successfully created user!',
            'accessToken'=> $token,
            ],201);
        }
        else{
            return response()->json(['error'=>'Provide proper details']);
        }
    }
</code></pre>

{% hint style="info" %}
Test your register api on **Postman**&#x20;

Select Method:<mark style="color:green;">`POST`</mark>

API: <mark style="color:red;">`http://127.0.0.1:8000/api/auth/register`</mark>
{% endhint %}

**Body** (Add body data on your postman like below table)

| Name         | Type | Description          |
| ------------ | ---- | -------------------- |
| `name`       | text | Name of the user     |
| `email`      | text | Email of the user    |
| `password`   | text | Password of the user |
| `c_password` | text | Confirm password     |

After this click on **send** button and get response like below.

**Response**

{% tabs %}
{% tab title="201" %}

```json
{
  "mesaage": "Successfully created user!",
  "accessToken": "9|nDyVOuzmExVZP7r0mq97f0rWdECWbRDvgmiKDkD1979a8a9e"
}
```

{% endtab %}
{% endtabs %}

**Capture screenshot of postman for demo purpose:**

<figure><img src="/files/GmeoRjclKJqXK0KeNcGz" alt=""><figcaption><p>Postman screenshot for register api</p></figcaption></figure>

### Login User API <a href="#step-4-login-user-api" id="step-4-login-user-api"></a>

In the same file `Http/Controllers/AuthController.php`, add below code before register method:

```php
/**
     * Login user and create token
    *
    * @param  [string] email
    * @param  [string] password
    * @param  [boolean] remember_me
    */

    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
            'remember_me' => 'boolean'
        ]);

        $credentials = request(['email','password']);
        if(!Auth::attempt($credentials))
        {
            return response()->json([
                'message' => 'Unauthorized'
            ],401);
        }

        $user = $request->user();
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->plainTextToken;

        return response()->json([
            'accessToken' =>$token,
            'token_type' => 'Bearer',
        ]);
    }
```

{% hint style="info" %}
Test your login api on **Postman**&#x20;

Select Method:<mark style="color:green;">`POST`</mark>

API: <mark style="color:red;">`http://127.0.0.1:8000/api/auth/login`</mark>
{% endhint %}

**Body** (Add body data on your postman like below table)

<table><thead><tr><th width="345">Name</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>email</code></td><td>text</td><td>Email of the user</td></tr><tr><td><code>password</code></td><td>text</td><td>Password of the user</td></tr></tbody></table>

After this click on **send** button and get response like below

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
    "accessToken": "9|nDyVOuzmExVZP7r0mq97f0rWdECWbRDvgmiKDkD1979a8a9e",
    "token_type": "Bearer"
}
```

{% endtab %}
{% endtabs %}

**Capture screenshot of postman for demo purpose:**

<figure><img src="/files/2q4bc104jEt5VxdizyYl" alt=""><figcaption><p>postman screenshot for login api</p></figcaption></figure>

### Get User API <a href="#step-5-get-user-api" id="step-5-get-user-api"></a>

In the same file `Http/Controllers/AuthController.php`, add below code after Login method:

```php
/**
 * Get the authenticated User
*
* @return [json] user object
*/
public function user(Request $request)
{
    return response()->json($request->user());
}
```

{% hint style="info" %}
Test your user api on **Postman**&#x20;

Select Method:<mark style="color:green;">`GET`</mark>

API: <mark style="color:red;">`http://127.0.0.1:8000/api/auth/user`</mark>
{% endhint %}

**Headers** (Add Headers data on your postman like below table)

<table><thead><tr><th width="345">Name</th><th>Description</th></tr></thead><tbody><tr><td>accept</td><td>application/json</td></tr><tr><td>Authorization</td><td>Bearer &#x3C;Token></td></tr></tbody></table>

After this click on **send** button and get response like below

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
    "id": "1",
    "name": "admin",
    "email": "admin@test.com",
    "email_verified_at": null,
    "created_at": "2024-4-02T06:21:13.000000Z",
    "updated_at": "2024-4-02T06:21:13.000000Z"
}
```

{% endtab %}
{% endtabs %}

**Capture screenshot of postman for demo purpose:**

<figure><img src="/files/JjQDCZ9HHRQXqRCu6NiD" alt=""><figcaption><p>postman screenshot for login api</p></figcaption></figure>

### Logout User API <a href="#step-6-logout-user-api" id="step-6-logout-user-api"></a>

In the same file `Http/Controllers/AuthController.php`, add below code after User method:

```php
/**
 * Logout user (Revoke the token)
*
* @return [string] message
*/
public function logout(Request $request)
{
    $request->user()->tokens()->delete();

    return response()->json([
    'message' => 'Successfully logged out'
    ]);

}
```

{% hint style="info" %}
Test your logout api on **Postman**&#x20;

Select Method:<mark style="color:green;">`GET`</mark>

API: <mark style="color:red;">`http://127.0.0.1:8000/api/auth/logout`</mark>
{% endhint %}

**Headers** (Add Headers data on your postman like below table)

<table><thead><tr><th width="345">Name</th><th>Description</th></tr></thead><tbody><tr><td>accept</td><td>application/json</td></tr><tr><td>Authorization</td><td>Bearer &#x3C;Token></td></tr></tbody></table>

After this click on **send** button and get response like below

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
    "message": "Successfully logged out"
}
```

{% endtab %}
{% endtabs %}

**Capture screenshot of postman for demo purpose:**

<figure><img src="/files/y3Rr1fSiqjsWv6uXPAQF" alt=""><figcaption><p>postman screenshot for logout api</p></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://phoenixcoded.gitbook.io/able-pro/vue-laravel/development/sanctum-authentication.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
