Making WordPress passwords work in Laravel

by Jeffrey van Rossum

When you are exporting WordPress users to a Laravel Application, you’ll notice that the hashed password from WordPress will not authenticate in Laravel.

Now instead of your users having to reset the password, you can follow the next steps.

Step 1

Install the Laravel WP Password package and follow the installation instructions.

Step 2

In this step, we are going to listen to failed login attempts. We do this by creating a so called event listener. Create a file called LogFailedAuthenticationAttempt.php and place it in app/Listeners. Next, implement the following code in that file:

<?php

namespace App\Listeners;

use Auth;
use Hash;
use App\User as User;
use Illuminate\Auth\Events\Failed;
use MikeMcLin\WpPassword\Facades\WpPassword;

class LogFailedAuthenticationAttempt
{
    /**
     * Handle the event.
     *
     * @param  Failed  $event
     * @return void
     */
    public function handle(Failed $event)
    {
        $user = User::where('email', $event->credentials['email'])->first();
        if ($user) {
            if (WpPassword::check($event->credentials['password'], $user->password)) {
                Auth::login($user);
                $user->password = Hash::make($event->credentials['password']);
                $user->save();
            }
        }
    }
}

If a Laravel login attempt fails, the above code will retry to authenticate but now with the WordPress password. If the authentication is successful, it will authenticate the user and also update the user password to a Laravel hashed variant. If authentication still fails, the script will simply return in the unauthenticated state.

Step 3

Now we need to register the event listener. We can do this in EventServiceProvider class, which you will find in the app/Providers folder.

Add the following under the $listen array (make sure to include the use statements at the top of your file):

use Illuminate\Auth\Events\Failed;
use App\Listeners\LogFailedAuthenticationAttempt;

Failed::class => [
    LogFailedAuthenticationAttempt::class,
],

That's it

It took me some time to figure out and I thought it might be useful for someone else too.

This post was last modified 12 May 2020
Did you like this post?

If you sign up for my newsletter, I can keep you up to date on more posts like this when they are published.