Verificación del email

Verificar el email en el registro de un usuario

Montaje de ficheros en el droplet:

sshfs usuario@alumno.xyz:/home/usuario/todo/ servidor -p 22

Laravel Email Verification

Un error que se puede encontrar es ‘Max key length is 1000 bytes’

Para solucionarlo hay que modificar el fichero app/Providers/AppServiceProvider.php para añadir la instrucción Schema::defaultStringLength(191) en el método boot:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Schema::defaultStringLength(191);
    }
}

Ejecutar de nuevo en consola la migración de las tablas para eliminar el error de max string:

cd todo
php artisan migrate:fresh

Preparación del modelo

Debemos implementar la interfaz MustVerifyEmail en el fichero app/Models/User.php y añadir ‘email_verified_at’ en $fillable:

<?php

namespace App\Models;

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

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

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

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

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
    
    public function tasks()
    {
    	return $this->hasMany(Task::class);
    }
}

Hacen falta 3 nuevas rutas para permitir la verificación del email en Laravel:

  • Una ruta para mostrar la notificación de verificación del email al usuario con un enlace para verificar el email
  • Una ruta para manejar el evento click del usuario cuando verifica su email (cuando recibe el mensaje en su correo y pulsa para verificarlo)
  • Una ruta para verificar de nuevo el email

Se modificará el fichero routes/web.php

Notificación de verificación del email:

Route::get('/email/verify', function () {
    return view('auth.verify-email');
})->middleware('auth')->name('verification.notice');

Manejo de la verificación del email:

use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\Request;


Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
    $request->fulfill();

    return redirect('/dashboard');
})->middleware(['auth', 'signed'])->name('verification.verify');

Reenvío del enlace de verificación del email

Route::post('/email/verification-notification', function (Request $request) {
    $request->user()->sendEmailVerificationNotification();

    return back()->with('message', 'Verification link sent!');
})->middleware(['auth', 'throttle:6,1'])->name('verification.send');

Fichero routes/web.php completo:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TasksController;
use App\Http\Controllers\EmailController;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::middleware(['auth:sanctum', 'verified'])->group(function(){
    Route::get('/dashboard',[TasksController::class, 'index'])->name('dashboard');

    Route::get('/task',[TasksController::class, 'add']);
    Route::post('/task',[TasksController::class, 'create']);
    
    Route::get('/task/{task}', [TasksController::class, 'edit']);
    Route::post('/task/{task}', [TasksController::class, 'update']);
});

Route::get('/sendemail', function () {
  try {
    $result = "Your email has been sent successfully";
    $data = array( 'name' => "LearningLaravel.net" );
    
    Mail::send('emails.learning', $data, function ($message) {
        $from = 'emisor@alumno.xyz';
        $name = 'nombreAlumno';
        // cambiar el email y poner uno propio
        $to = 'paco.portada@protonmail.com';
        $subject = "Learning Laravel test email";   
        $message->from($from, $name);
        $message->to($to);
        $message->subject($subject);
        });
    } catch (Exception $e) {
            $result = $e->getMessage();
    }
    return $result;
});

Route::get('/email', [EmailController::class, 'create']);
Route::post('/email', [EmailController::class, 'sendEmail'])->name('send.email');

Route::get('/email/verify', function () {
    return view('auth.verify-email');
})->middleware('auth')->name('verification.notice');

Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
    $request->fulfill();

    return redirect('/dashboard');
})->middleware(['auth', 'signed'])->name('verification.verify');

Route::post('/email/verification-notification', function (Request $request) {
    $request->user()->sendEmailVerificationNotification();

    return back()->with('message', 'Verification link sent!');
})->middleware(['auth', 'throttle:6,1'])->name('verification.send');

 

 

Deja una respuesta