Laravel Passwordless Authentication Part 1

6 months ago admin Laravel

In this tutorial, we will see how to create a Laravel passwordless authentication system, the user will create an account and once created he will receive an email with a unique signature to log in, the same process will happen when he logs in.


Update the user's migration

First, let's update the user's migration we set the password default value to null because we will not use it for authenticating users.

Next, run php artisan migrate to create the database and migrate the tables.

                                                        
                                                                                                                        
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};

Generating the mailable with the markdown template

Next, let's generate the mailable with the markdown template we name it 'LoginLink' with a template named 'login_link' inside the folder 'emails'.

                                                            
                                                                                                                                
php artisan make:mail LoginLink --markdown=emails.login_link

Update the mailable content

Next, let's update the 'LoginLink' content we create a temporary signed URL, it takes the route as the first param, and the time of expiration here it's 10 minutes as the second param, and finally the user email as the third param. 

                                                            
                                                                                                                                
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\URL;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Queue\SerializesModels;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Contracts\Queue\ShouldQueue;

class LoginLink extends Mailable
{
    use Queueable, SerializesModels;

    public string $url;

    /**
     * Create a new message instance.
     */
    public function __construct(string $email)
    {
        //
        $this->url = URL::temporarySignedRoute('user.session', now()->addMinutes(10), ['email' => $email]);
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Your login Link',
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            markdown: 'emails.login_link',
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        return [];
    }
}

Update the markdown template

Next, let's update the 'login_link.blade.php' content inside we add the button that contains the link for authenticating the user.

                                                            
                                                                                                                                
<x-mail::message>
# Your login link

<x-mail::button :url="$url">
Login
</x-mail::button>

Thanks,<br>
{{ config('app.name') }}
</x-mail::message>


Update the env file to send emails

To send emails we will use the Mailtrap service, you need to create an account choose Laravel from the integrations dropdown menu, and grab your credentials.

Inside the .env file add the credentials.

                                                            
                                                                                                                                
MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME='Your username'
MAIL_PASSWORD='Your password'
MAIL_FROM_NAME="${APP_NAME}"

Related Tuorials

How to Check if a Record Does Not Exist in Laravel

in this lesson, we will see how to check if a record does not exist in laravel, sometimes you need t...


How to Check if a Record Exists in Laravel

in this lesson, we will see how to check if a record exists in laravel, sometimes you need to check...


How to Decrement Multiple Fields in Laravel

In this lesson, we will see how to decrement multiple fields in Laravel, in the old versions of lara...


How to Increment Multiple Fields in Laravel

In this lesson, we will see how to increment multiple fields in Laravel, in the old versions of lara...


How to Use the Same Request Validation Rules for Storing and Updating in Laravel

In this lesson, we will see how to use the same request validation rules for storing and updating in...


How to Go Back to the Previous URL in Laravel Blade

In this lesson, we will see how to go back to the previous URL in Laravel Blade, sometimes we need t...


How to Add Additional Data to The Resource JSON Response in Laravel

In this lesson, we will see how to add additional data to the resource JSON response in Laravel, let...


How to Specify the Attributes to be Returned in the Laravel Find Method

In this lesson, we will see how to specify the attributes to be returned in the Laravel find method,...


How to Get Data Using Where All in Laravel

In this lesson, we will see how to get data using Where All in Laravel, the Where All method is used...


How to Get Data Using Where Any in Laravel

In this lesson, we will see how to get data using Where Any in Laravel, the Where Any method is used...