---
description: >-
  https://medium.com/modulr/api-rest-with-laravel-5-6-passport-authentication-reset-password-part-4-50d27455dcca
---

# API Rest with Laravel 5.6 Passport Authentication — Reset Password (Part 4)

## API Rest with Laravel 5.6 Passport Authentication — Reset Password (Part 4) <a href="#id-74d9" id="id-74d9"></a>

[![Alfredo Barron](https://miro.medium.com/fit/c/96/96/1*_RpT5iWcS972YjR9jl30rA.jpeg)](https://medium.com/@alfredobarron?source=post_page-----50d27455dcca----------------------)[Alfredo Barron](https://medium.com/@alfredobarron?source=post_page-----50d27455dcca----------------------)Follow[Aug 2, 2018](https://medium.com/modulr/api-rest-with-laravel-5-6-passport-authentication-reset-password-part-4-50d27455dcca?source=post_page-----50d27455dcca----------------------) · 6 min read

We will learn to create a password reset system![Image for post](https://miro.medium.com/max/60/1*5nfrrzfCQlFFIuVV7quS5A.jpeg?q=20)![Image for post](https://miro.medium.com/max/2400/1*5nfrrzfCQlFFIuVV7quS5A.jpeg)[https://www.vecteezy.com](https://www.vecteezy.com/)

## Step 1. Update migration <a href="#id-208a" id="id-208a"></a>

```
php artisan make:model PasswordReset -m
```

In first step, we require to update the migration file `database/migrations/xxx_create_password_resets_table.php` like bellow code:

```
public function up()
{
    Schema::create('password_resets', function (Blueprint $table) {
        $table->increments('id');
        $table->string('email')->index();
        $table->string('token');
        $table->timestamps();
    });
}
```

## Step 2. Create PasswordReset model <a href="#id-70ec" id="id-70ec"></a>

Open your terminal or command prompt and run bellow command:

```
php artisan make:model PasswordReset
```

This command will create `app/PasswordReset.php` file, in this file set fillable inputs.

```
class PasswordReset extends Model
{
    protected $fillable = [
        'email', 'token'
    ];
}
```

## Step 3. Create Notifications <a href="#id-4e89" id="id-4e89"></a>

We create two notifications `PaswordResetRequest` and `PasswordResetSuccess`, in your terminal or command prompt run bellow commands:

```
php artisan make:notification PasswordResetRequestphp artisan make:notification PasswordResetSuccess
```

This command will create `app/Notifications/PasswordResetRequest.php` and `app/Notifications/PasswordResetSuccess.php` files.

In the `PasswordResetRequest.php` file add the next code:

```
<?phpnamespace App\Notifications;use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;class PasswordResetRequest extends Notification implements ShouldQueue
{
    use Queueable;    protected $token;    /**
    * Create a new notification instance.
    *
    * @return void
    */
    public function __construct($token)
    {
        $this->token = $token;
    }    /**
    * Get the notification's delivery channels.
    *
    * @param  mixed  $notifiable
    * @return array
    */
    public function via($notifiable)
    {
        return ['mail'];
    }     /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
     public function toMail($notifiable)
     {
        $url = url('/api/password/find/'.$this->token);        return (new MailMessage)
            ->line('You are receiving this email because we        received a password reset request for your account.')
            ->action('Reset Password', url($url))
            ->line('If you did not request a password reset, no further action is required.');
    }    /**
    * Get the array representation of the notification.
    *
    * @param  mixed  $notifiable
    * @return array
    */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}
```

In the `PasswordResetSuccess.php` file add the next code:

```
<?phpnamespace App\Notifications;use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;class PasswordResetSuccess extends Notification implements ShouldQueue
{
    use Queueable;
    
    /**
    * Create a new notification instance.
    *
    * @return void
    */
    public function __construct()
    {
        //
    }    /**
    * Get the notification's delivery channels.
    *
    * @param  mixed  $notifiable
    * @return array
    */
    public function via($notifiable)
    {
        return ['mail'];
    }    /**
    * Get the mail representation of the notification.
    *
    * @param  mixed  $notifiable
    * @return \Illuminate\Notifications\Messages\MailMessage
    */
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->line('You are changed your password successful.')
            ->line('If you did change password, no further action is required.')
            ->line('If you did not change password, protect your account.');
    }/**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}
```

## Step 4. Create API Routes <a href="#id-491d" id="id-491d"></a>

We will create api routes. Laravel provide `routes/api.php` file for write web services route. So, let’s add new route on that file.

```
<?phpuse Illuminate\Http\Request;...Route::group([    
    'namespace' => 'Auth',    
    'middleware' => 'api',    
    'prefix' => 'password'
], function () {    
    Route::post('create', 'PasswordResetController@create');
    Route::get('find/{token}', 'PasswordResetController@find');
    Route::post('reset', 'PasswordResetController@reset');
});
```

## Step 5: Install Dependencies <a href="#id-5f3f" id="id-5f3f"></a>

We use [Carbon](https://carbon.nesbot.com/) package to help with dates, in your terminal run bellow command:

```
composer require nesbot/carbon
```

## Step 6: Create Controller <a href="#id-174d" id="id-174d"></a>

In this step we have to create new controller and three api method. So let’s create `PasswordResetController` and put bellow code:

```
<?phpnamespace App\Http\Controllers\Auth;use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Notifications\PasswordResetRequest;
use App\Notifications\PasswordResetSuccess;
use App\User;
use App\PasswordReset;class PasswordResetController extends Controller
{
    /**
     * Create token password reset
     *
     * @param  [string] email
     * @return [string] message
     */
    public function create(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
        ]);        $user = User::where('email', $request->email)->first();        if (!$user)
            return response()->json([
                'message' => 'We can't find a user with that e-mail address.'
            ], 404);        $passwordReset = PasswordReset::updateOrCreate(
            ['email' => $user->email],
            [
                'email' => $user->email,
                'token' => str_random(60)
             ]
        );        if ($user && $passwordReset)
            $user->notify(
                new PasswordResetRequest($passwordReset->token)
            );        return response()->json([
            'message' => 'We have e-mailed your password reset link!'
        ]);
    }    /**
     * Find token password reset
     *
     * @param  [string] $token
     * @return [string] message
     * @return [json] passwordReset object
     */
    public function find($token)
    {
        $passwordReset = PasswordReset::where('token', $token)
            ->first();        if (!$passwordReset)
            return response()->json([
                'message' => 'This password reset token is invalid.'
            ], 404);        if (Carbon::parse($passwordReset->updated_at)->addMinutes(720)->isPast()) {
            $passwordReset->delete();
            return response()->json([
                'message' => 'This password reset token is invalid.'
            ], 404);
        }        return response()->json($passwordReset);
    }     /**
     * Reset password
     *
     * @param  [string] email
     * @param  [string] password
     * @param  [string] password_confirmation
     * @param  [string] token
     * @return [string] message
     * @return [json] user object
     */
    public function reset(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string|confirmed',
            'token' => 'required|string'
        ]);        $passwordReset = PasswordReset::where([
            ['token', $request->token],
            ['email', $request->email]
        ])->first();        if (!$passwordReset)
            return response()->json([
                'message' => 'This password reset token is invalid.'
            ], 404);        $user = User::where('email', $passwordReset->email)->first();        if (!$user)
            return response()->json([
                'message' => 'We can't find a user with that e-mail address.'
            ], 404);        $user->password = bcrypt($request->password);
        $user->save();        $passwordReset->delete();        $user->notify(new PasswordResetSuccess($passwordReset));        return response()->json($user);
    }
}
```

> Now we are ready to run our example so run bellow command to quick run:

```
php artisan serve
```

## Tests <a href="#a30c" id="a30c"></a>

Now, we can simple test by rest client tools (Postman), So I test it and you can see below screenshots.

> In this api you have to set two header as listed below:

```
Content-Type: application/json
X-Requested-With: XMLHttpRequest
```

Request Password Reset![Image for post](https://miro.medium.com/max/60/1*mVWfioIvPKls3VY8Akqx-w.png?q=20)![Image for post](https://miro.medium.com/max/1204/1*mVWfioIvPKls3VY8Akqx-w.png)

When request password reset will created token in data base![Image for post](https://miro.medium.com/max/60/1*-zqcuSiU644K_Qcq-6v8cg.png?q=20)![Image for post](https://miro.medium.com/max/1545/1*-zqcuSiU644K_Qcq-6v8cg.png)

When request password reset will receive a email with the link to Reset Password.![Image for post](https://miro.medium.com/max/60/1*DsJxF8A0auf3OOeEUOYgqg.png?q=20)![Image for post](https://miro.medium.com/max/1058/1*DsJxF8A0auf3OOeEUOYgqg.png)

Find Password Reset

_If the token is active response with token data_![Image for post](https://miro.medium.com/max/60/1*XJdlmjYHa0GNBJPWzDCzpg.png?q=20)![Image for post](https://miro.medium.com/max/1204/1*XJdlmjYHa0GNBJPWzDCzpg.png)

_If the token is not active the response is a 404 error_![Image for post](https://miro.medium.com/max/60/1*hMg2awvSl_A4EAZAhRs5Qg.png?q=20)![Image for post](https://miro.medium.com/max/1205/1*hMg2awvSl_A4EAZAhRs5Qg.png)

Reset Password

_If the token is active response with User data_![Image for post](https://miro.medium.com/max/60/1*SyUILK7e8p5CC_ku3oY4Zg.png?q=20)![Image for post](https://miro.medium.com/max/2408/1*SyUILK7e8p5CC_ku3oY4Zg.png)

_If the token is not active the response is a 404 error_![Image for post](https://miro.medium.com/max/60/1*DHwc0wMzCzC3K6PrJSC8cA.png?q=20)![Image for post](https://miro.medium.com/max/2415/1*DHwc0wMzCzC3K6PrJSC8cA.png)

> Thanks for reading! I’m Alfredo Barrón, Feel free to connect with me via [Twitter](https://twitter.com/AlfredoBarronC).

Part 1. [Passport Authentication](https://medium.com/modulr/create-api-authentication-with-passport-of-laravel-5-6-1dc2d400a7f)\
Part 2. [Confirm account + notifications](https://medium.com/modulr/create-api-authentication-passport-in-laravel-5-6-confirm-account-notifications-part-2-5e221b021f07)\
Part 3. [Generate avatar](https://medium.com/modulr/api-rest-with-laravel-5-6-passport-authentication-generate-avatar-part-3-d92ec7935eff)\
**Part 4. Reset Password**\
Part 5. [Send Notifications with Queues on Redis](https://medium.com/modulr/api-rest-with-laravel-5-6-175eea5db3e8)

### Resources <a href="#id-5231" id="id-5231"></a>

[GitHub](https://github.com/modulr/api-laravel-passport)\
[Postman collections](https://documenter.getpostman.com/view/1657780/RW1ejGzL)
