Skip to content

Instantly share code, notes, and snippets.

@Eyad-Bereh
Last active April 6, 2023 07:51
Show Gist options
  • Save Eyad-Bereh/9f85ac61e46e5dde8aad06998e6b8202 to your computer and use it in GitHub Desktop.
Save Eyad-Bereh/9f85ac61e46e5dde8aad06998e6b8202 to your computer and use it in GitHub Desktop.
Laravel E-mail verification without having the user to be logged in
<?php
// The original Illuminate\Foundation\Auth\EmailVerificationRequest which contains code that requires user to be logged in
// So that the verification process can work, since it's retrieving the user from the $request object
// Here, we are reading the id parameter from the route and using it to find the correct User model instead
// IMPORTANT NOTES:
// 1. This will only work with the App\Models\User model
// 2. Don't forget to remove the (auth) middleware from the (verification.verify) route
namespace App\Http\Requests;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Http\FormRequest;
class EmailVerificationRequest extends FormRequest
{
// Declare user as a field to make it accessible throughout the whole class
private User $user;
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
$id = $this->route("id"); // Get the id
$hash = $this->route("hash"); // Get the hash
$this->user = User::findOrFail($id); // Get the user
// From this point, you can access the user object anywhere in the class
// Notice that we're just replacing the calls of ($this->user()) with ($this->user)
if (!hash_equals((string) $this->user->getKey(), (string) $id)) {
return false;
}
if (!hash_equals(sha1($this->user->getEmailForVerification()), (string) $hash)) {
return false;
}
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
/**
* Fulfill the email verification request.
*
* @return void
*/
public function fulfill()
{
if (!$this->user->hasVerifiedEmail()) {
$this->user->markEmailAsVerified();
event(new Verified($this->user));
}
}
/**
* Configure the validator instance.
*
* @param \Illuminate\Validation\Validator $validator
* @return void
*/
public function withValidator($validator)
{
return $validator;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment