Laravel 10 Inertia & Vue 3 Authentication with Email Verification Part 1

1 year ago admin Laravel

In today's, tutorial we are going to see how to register & login users using Laravel, Inertia js, and Vue js, we will also see how to add email verification to our authentication system.


Create the migration

First, we create the user migration.

                                                    
                                                                                                                
<?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');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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


Create the controller

Next, we create the AuthController.

                                                        
                                                                                                                        
<?php

namespace App\Http\Controllers;

use App\Models\User;
use Inertia\Inertia;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Auth\Events\Registered;

class AuthController extends Controller
{
    //
    public function register() {
        return Inertia::render('User/Register');
    }

    public function store(Request $request) {
        $this->validate($request,[
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        event(new Registered($user));
        
        auth()->login($user);

        $request->session()->regenerate();

        return redirect()->route('home');
    }

    public function login() {
        return Inertia::render('User/Login');
    }

    public function auth(Request $request) {
        $this->validate($request,[
            'email' => 'required|email',
            'password' => 'required|min:6',
        ]);

        if(auth()->attempt([
            'password' => $request->password,
            'email' => $request->email,
        ])) {
            $request->session()->regenerate();
            return redirect()->route('home');
        }else {
            return Inertia::render('User/Login', [
                'failed' => "These credentials do not match any of our records!"
            ]);
        }
    }

    public function logout(Request $request) {
        auth()->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('login');
    }

    public function emailVerification() {
        if(auth()->user()->hasVerifiedEmail()) {
            return redirect()->back();
        }
        return Inertia::render('User/VerifyEmail');
    }

}


Update the user model

Next, let's update the user model.

                                                        
                                                                                                                        
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}


Add routes

Next, let's add the routes.

                                                        
                                                                                                                        
<?php

use Inertia\Inertia;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use Illuminate\Foundation\Auth\EmailVerificationRequest;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::middleware('auth')->group(function() {
    Route::get('/', function() {
        return Inertia::render('Home');
    })->middleware('verified')->name('home');

    Route::post('user/logout', [AuthController::class, 'logout'])->name('logout');
    
    Route::get('/email/verify', [AuthController::class, 'emailVerification'])->middleware('auth')->name('verification.notice');
   
    Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
        $request->fulfill();
     
        return redirect()->route('home')->with([
            'message' => 'Email verified successfully',
            'class' => 'alert alert-success'
        ]);
    })->middleware('signed')->name('verification.verify');
    
    Route::post('/email/verification-notification', function (Request $request) {
        $request->user()->sendEmailVerificationNotification();
     
        return redirect()->back()->with([
            'message' => 'Verification link sent!',
            'class' => 'alert alert-success'
        ]);
    })->middleware('throttle:6,1')->name('verification.send');
});

Route::middleware('guest')->group(function() {
    Route::get('user/register', [AuthController::class, 'register'])->name('register');
    
    Route::post('user/register', [AuthController::class, 'store'])->name('register');
    
    Route::get('user/login', [AuthController::class, 'login'])->name('login');
    
    Route::post('user/login', [AuthController::class, 'auth'])->name('login');
});

Add Register Component

Next, inside js/Pages let's create a new folder "User" inside we add a new component "Register.vue".

                                                        
                                                                                                                        
<template>
    <div class="container">
        <div className="row my-5">
            <div className="col-md-6 mx-auto">
                <div className="card">
                    <div className="card-header bg-white">
                        <h5 className="text-center mt-2">
                            Register
                        </h5>
                    </div>
                    <div className="card-body">
                        <form @submit.prevent="register" className="mt-5">
                            <div className="mb-3">
                                <label htmlFor="name" className="form-label">Name*</label>
                                <input 
                                    type="text" 
                                    v-model="form.name"
                                    className="form-control" 
                                    placeholder="Name*">
                                <div v-if="form.errors.name" class="text-white bg-danger p-2 rounded my-2">{{ form.errors.name }}</div>
                            </div>
                            <div className="mb-3">
                                <label htmlFor="email" className="form-label">Email*</label>
                                <input 
                                    type="text" 
                                    v-model="form.email"
                                    className="form-control" 
                                    placeholder="Email*">
                                <div v-if="form.errors.email" class="text-white bg-danger p-2 rounded my-2">{{ form.errors.email }}</div>
                            </div>
                            <div className="mb-3">
                                <label htmlFor="password" className="form-label">Password*</label>
                                <input 
                                    type="password" 
                                    v-model="form.password"
                                    className="form-control" 
                                    placeholder="Password*">
                                <div v-if="form.errors.password" class="text-white bg-danger p-2 rounded my-2">{{ form.errors.password }}</div>
                            </div>
                            <div className="mb-3">
                                <button
                                    type="submit" 
                                    className="btn btn-primary">
                                    Register
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { useForm } from "@inertiajs/vue3";

    const form = useForm({
        name: '',
        email: '',
        password: '',
    });

    const register = () => {
        form.post(route('register'));
    }
</script>

<style>

</style>

Related Tuorials

How to Conditionally Include a Blade Template in Laravel

In this lesson, we will see how to conditionally include a blade template in Laravel.Sometimes,...


How to Include a Blade Template Only if it Exists in Laravel

In this lesson, we will see how to include a blade template only if it exists in Laravel.Sometimes,&...


How to Pass a Variable to Include in Laravel

In this lesson, we will see how to pass a variable to include in Laravel. Sometimes, we want to pass...


How to the Get the Previous and Next Posts in Laravel

In this lesson, we will see how to get the previous and next posts in Laravel, sometimes when you ge...


How Do you Format a Number as K/M/B in Laravel

In this lesson, we will see how to format a number as K/M/B in Laravel, sometimes we want to display...


How to Override Laravel Fortify Default Registration Redirect

In this lesson, we will see how to override Laravel Fortify default registration redirect, sometimes...


How to Override Laravel Fortify Default Login Redirect

In this lesson, we will see how to override Laravel Fortify default login redirect, sometimes when w...


How to Use the Same Validation Form Request for both Create and Update in Laravel

In this lesson, we will see how to use the same validation form request for both create and update i...


How to Get Raw SQL Output from the Eloquent Model in Laravel 11

In this lesson, we will see how to get raw SQL output from the eloquent model in Laravel 11, sometim...


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...