jrean/laravel-user-verification is a PHP package built for Laravel 5.* & 6.* & 7.* & 8.* toeasily handle a user verification and validate the e-mail.
This package is Laravel 8.0 compliant.
laravel/branch | 2.2 | 3.0 | 4.1 | 5.0 | 6.0 | 7.0 | 8.0 | 9.0 | master |
---|---|---|---|---|---|---|---|---|---|
5.0.* | x | ||||||||
5.1.* | x | ||||||||
5.2.* | x | ||||||||
5.3.* | x | ||||||||
5.4.* | x | ||||||||
5.5.* | x | ||||||||
5.6.* | x | ||||||||
5.7.* | x | ||||||||
5.8.* | x | ||||||||
6.0.* | x | ||||||||
7.0.* | x | ||||||||
8.0.* | x | x |
This project can be installed via Composer. To getthe latest version of Laravel User Verification, add the following line to therequire block of your composer.json file:
{
"require": {
"jrean/laravel-user-verification": "dev-master"
}
}
You'll then need to run composer install
or composer update
to download thepackage and have the autoloader updated.
Or run the following command:
composer require jrean/laravel-user-verification
Once Larvel User Verification is installed, you need to register the service provider in config/app.php
.Make sure to add the following line above the RouteServiceProvider
.
Jrean\UserVerification\UserVerificationServiceProvider::class,
You may add the following aliases
to your config/app.php
:
'UserVerification' => Jrean\UserVerification\Facades\UserVerification::class,
Publish the package config file by running the following command:
php artisan vendor:publish --provider="Jrean\UserVerification\UserVerificationServiceProvider" --tag="config"
The model representing the User
must implement the authenticatableinterface Illuminate\Contracts\Auth\Authenticatable
which is the default withthe Eloquent User
model.
The table representing the user must be updated with two new columns, verified
and verification_token
.This update will be performed by the migrations included with this package.
It is mandatory that the two columns are on the same table where the user'se-mail is stored. Please make sure you do not already have those fields onyour user table.
To run the migrations from this package use the following command:
php artisan migrate --path="/vendor/jrean/laravel-user-verification/src/resources/migrations"
The package tries to guess your user
table by checking what is set in the auth providers users settings.If this key is not found, the default App\User
will be used to get the table name.
To customize the migration, publish it with the following command:
php artisan vendor:publish --provider="Jrean\UserVerification\UserVerificationServiceProvider" --tag="migrations"
This package provides an optional middleware throwing a UserNotVerifiedException
.Please refer to the Laravel Documentation to learn more about how to work with the exception handler.
To register the default middleware add the following lines to the $routeMiddleware
array within the app/Http/Kernel.php
file:
protected $routeMiddleware = [
// …
'isVerified' => \Jrean\UserVerification\Middleware\IsVerified::class,
Apply the middleware on your routes:
Route::group(['middleware' => ['isVerified']], function () {
// …
Create your own custom middleware using the following artisan command:
php artisan make:middleware IsVerified
For more details about middlewares, please refer to the Laravel Documentation.
This package provides a method to send an e-mail with a link containing the verification token.
send(AuthenticatableContract $user, $subject, $from = null, $name = null)
By default the package will use the from
and name
values defined into theconfig/mail.php
file:
'from' => ['address' => '', 'name' => ''],
If you want to override the values, simply set the $from
and (optional)$name
parameters.
Refer to the Laravel documentation for theproper e-mail component configuration.
The user will receive an e-mail with a link leading to the getVerification()
method (endpoint). The view will receive a $user
variable which contains theuser details such as the verification token.
The package allow you to use both traditional blade view files and markdown.
By default a sample e-mail view is loaded to get you started with:
Click here to verify your account: <a href="{{ $link = route('email-verification.check', $user->verification_token) . '?email=' . urlencode($user->email) }}">{{ $link }}</a>
If you prefer to use Markdown instead, update the package config fileuser-verification.php
in the config
directory and replace the following:
'email' => [
'type' => 'default',
],
by:
'email' => [
'type' => 'markdown',
],
If you want to customize the e-mail views, run the following command to publishthem and edit them to your needs:
The URL must contain the verification token as parameter + (mandatory) aquery string with the user's e-mail as parameter.
php artisan vendor:publish --provider="Jrean\UserVerification\UserVerificationServiceProvider" --tag="views"
The view will be available in the resources/views/vendor/laravel-user-verification/
directory.
This package throws several exceptions. You are free to use try/catch
statements or to rely on the Laravel built-in exceptions handler.
ModelNotCompliantException
The model instance provided is not compliant with this package. It mustimplement the authenticatable interfaceIlluminate\Contracts\Auth\Authenticatable
TokenMismatchException
Wrong verification token.
UserIsVerifiedException
The given user is already verified.
UserNotVerifiedException
The given user is not yet verified.
UserNotFoundException
No user found for the given e-mail address.
UserHasNoEmailException
User email property is null or empty.
By default the user-verification.blade.php
view will be loaded for the verification error route /email-verification/error
. If an error occurs, the user will be redirected to this route and this view will be rendered.
To customize the view, publish it with the following command:
php artisan vendor:publish --provider="Jrean\UserVerification\UserVerificationServiceProvider" --tag="views"
The view will be available in the resources/views/vendor/laravel-user-verification/
directory and can be customized.
By default this packages ships with two routes.
Route::get('email-verification/error', 'Auth\RegisterController@getVerificationError')->name('email-verification.error');
Route::get('email-verification/check/{token}', 'Auth\RegisterController@getVerification')->name('email-verification.check');
To define your own custom routes, put the package service provider call before the RouteServiceProvider
call in the config/app.php
file.
/*
* Package Service Providers...
*/
Jrean\UserVerification\UserVerificationServiceProvider::class,
/*
* Application Service Providers...
*/
// ...
App\Providers\RouteServiceProvider::class,
Then, add your custom routes in your route file.
The package offers three (3) traits for a quick implementation.Only VerifiesUsers
trait is mandatory and includes RedirectsUsers
.
Jrean\UserVerification\Traits\VerifiesUsers
Jrean\UserVerification\Traits\RedirectsUsers
and:
Jrean\UserVerification\Traits\UserVerification
This last one offers two methods that can be added to the User
model.
isVerified
checks if a user is marked as verified.isPendingVerification
checks if a verification process has been initiated for a user.Add the use statement to your User
model and use the UserVerification
within the class:
The two (2) following methods are included into the VerifiesUsers
trait andcalled by the default package routes.
getVerification(Request $request, $token)
Handle the user verification.
getVerificationError()
Do something if the verification fails.
The package public API offers eight (8) methods.
generate(AuthenticatableContract $user)
Generate and save a verification token for the given user.
send(AuthenticatableContract $user, $subject = null, $from = null, $name = null)
Send by e-mail a link containing the verification token.
sendQueue(AuthenticatableContract $user, $subject = null, $from = null, $name = null)
Queue and send by e-mail a link containing the verification token.
sendLater($seconds, AuthenticatableContract $user, $subject = null, $from = null, $name = null)
Send later by e-mail a link containing the verification token.
process($email, $token, $userTable)
Process the token verification for the given e-mail and token.
For the sendQueue
, sendLater
andsendLaterOn
methods, you must configure your queuesbefore using this feature.
The package offers a facade UserVerification::
.
To customize the package behaviour and the redirects you can implement andcustomize six (6) attributes/properties:
$redirectIfVerified = '/';
Where to reditect if the authenticated user is already verified.
$redirectAfterVerification = '/';
Where to redirect after a successful verification token verification.
$redirectIfVerificationFails = '/email-verification/error';
Where to redirect after a failling token verification.
$verificationErrorView = 'laravel-user-verification::user-verification';
Name of the view returned by the getVerificationError method.
$verificationEmailView = 'laravel-user-verification::email'
Name of the default e-mail view.
$userTable = 'users';
Name of the default table used for managing users.
To customize the translations you may publish the files to your resources/lang/vendor
folder using the following command:
php artisan vendor:publish --provider="Jrean\UserVerification\UserVerificationServiceProvider" --tag="translations"
This will add laravel-user-verification/en/user-verification.php
to your vendor folder. By creating new language folders, like de
or fr
and placing a user-verification.php
with the translations inside, you can add translations for other languages. You can find out more about localization in the Laravel documentation.
If you wish to automaticaly log in the user after the verification process, update the package config file user-verification.php
in the config directory and replace the following:
'auto-login' => false,
by:
'auto-login' => true,
You can customize the package behaviour by overriding/overwriting thepublic methods and the attributes/properties. Dig into the source.
This package doesn't require the user to be authenticated to perform theverification. You are free to implement any flow you may want to achieve.
This package wishes to let you be creative while offering you a predefinedpath. The following guidelines assume you have configured Laravel for thepackage as well as created and migrated the migration according to thisdocumentation and the previous documented steps.
Note that by default the behaviour of Laravel is to return an authenticateduser after the registration step.
The following code sample aims to showcase a quick and basic implementationfollowing Laravel logic. You are free to implement the way you want.It is highly recommended to read and to understand the way Laravel implementsregistration/authentication.
Edit the app\Http\Controllers\Auth\RegisterController.php
file.
VerifiesUsers
trait (mandatory)RedirectsUsers
trait included by theVerifiesUsers
trait. (not mandatory)register()
method (mandatory)namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use Jrean\UserVerification\Traits\VerifiesUsers;
use Jrean\UserVerification\Facades\UserVerification;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
use VerifiesUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
// Based on the workflow you need, you may update and customize the following lines.
$this->middleware('guest', ['except' => ['getVerification', 'getVerificationError']]);
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
/**
* Handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
$user = $this->create($request->all());
event(new Registered($user));
$this->guard()->login($user);
UserVerification::generate($user);
UserVerification::send($user, 'My Custom E-mail Subject');
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
}
At this point, after registration, an e-mail is sent to the user.Click the link within the e-mail and the user will be verified against thetoken.
If you want to perform the verification against an authenticated user you mustupdate the middleware exception to allow getVerification
andgetVerificationError
routes to be accessed.
$this->middleware('guest', ['except' => ['getVerification', 'getVerificationError']]);
If you want to regenerate and resend the verification token, you can do this with the following two lines:
UserVerification::generate($user);
UserVerification::send($user, 'My Custom E-mail Subject');
The generate
method will generate a new token for the given user and change the verified
column to 0. The send
method will send a new e-mail to the user.
For Laravel Spark integration, follow this article from Ian Fagg
Feel free to comment, contribute and help. 1 PR = 1 feature.
Laravel User Verification is licensed under The MIT License (MIT).
今天在调试 laravel passport 登录后,直接通过 Auth::guard('api')->user(),获取登录用户信息,返回 null。 看代码: 代理登录方法 public function login($mobile, $password) { if (auth()->attempt(['mobile' => $mobile, 'p
-- 文章仅供个人学习参考,如有不恰当的地方,希望前辈们指教。-- 1、修改config\auth.php配置文件 'model' => App\Model\Users::class, 'table' => 'users', 2、 修改Users模型类如下: use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Authentica
一大早的,打开项目就发现报了如上错误。看了下报错信息,原来是redis的错误。意思是没有经过授权验证。这就很奇怪了,昨天还是好好的。 1、找到reids-cli //找到redis-cli的位置 whereis redis-cli 2、进入redis /use/local/redis-cli -a 密码 //进去之后查看所有的key keys * //报错:NOAUTH Authenticatio
第一步:配置方面 在config下的auth.php配置guards 和 providers 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'cloud' => [
PDOException in Connector.php line 55:SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES) 出现问题解决方法如下 1.确认database.php文件配置正确。 首先检查database.php中自己填写的信息是正确的。 2.检查
这几天学习Laravel框架遇到了数据库方面的问题。 PDOException in Connector.php line 55:SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES) 出现问题解决方法如下 1.确认database.php文件配置正确。 首先检查dat
因为 laravel 5.2 更新了路由策略......... 所以所有路由都应该写在中间件web的下面 Route::group(['middleware' => 'web'], function () { // your routes }); 当然也可以把web中间件放到全局的中间件里面去 ,在app/Http/Kernel.php文件中,然后把web中间件删掉 protect
很多应用是需要登陆后才能操作,Laravel提供了一个auth工具来实现用户的认证功能。并且有一个config/auth.php来配置auth工具。大概看一下auth工具的常用方法 Auth::check();// 判断当前用户是否未登录 Auth::guest();// 判断当前用户是否未登录,与 check() 相反 Auth::guard();// 自定义看守器 默认为 `web` Auth
一、配置 config/auth.php <?php return [ 'defaults' => [ 'guard' => 'web', 'passwords' => 'users', ], 'guards' => [ 'web' => [ 'driver' => 'session',//指向lll
Laravel 5.6 中文文档 http://laravelacademy.org/laravel-docs-5_6 http://laravelacademy.org/post/8900.html http://laravelacademy.org/post/8851.html 注:想要快速上手?只需要在新安装的 Laravel 应用下运行 php artisan make:auth 和 ph
语言包的问题 laravel 5.3 更换语言包 96 假行僧396741 关注 2016.12.15 15:36* 字数 280 阅读 4457评论 0喜欢 4 Laravel-lang Laravel 5 语言包,包含 52 种语言, 基于 caouecs/Laravel-lang. trans() 函数根据你的 [本地化文件] 翻译指定的语句 安装 composer require
原文链接:https://www.jianshu.com/p/e131af68e6b3 1. 目的 本文来简单的讲解 laravel 中guard 用法,实现 admin 和 user 多表登陆(只讲了登陆功能,其它的功能都一样,不多赘述) 2. 配置 首先需要在 <code>auth.php</code> 中配置 admin 的 <code>guards</code> 和 <code>pro
直接修改模型名称从User ->AdminUser class AdminUser extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillabl
简介 认证系统主要由两部分组成: guards 每个请求中,怎么认证用户 例如:通过 session guard providers 怎样从持久化存储中获取用户 例如:通过 Eloquent, DB 一般来说,不用修改默认的认证配置 认证快速开始 php artisan make:auth 修改跳转地址 protected $redirectTo = '/'; # 方法的优先级高于属性定义 p
因Laravel5.3+以后__construct函数中无法获取Auth::user()信息。 故我在做根据用户编号获取菜单信息时这步非常困难,现将解决解决方案写在下面。 因Laravel框架加载流程 middleware执行总在__construct函数之后运行,故$this->middleware(‘checkMenu’); 写在构造函数的哪个位置都会最后执行。 创建中间件 //在Middle
今天遇到了一个问题, 配置了数据库的配置文件,并且确保都没有问题,但是启动项目的时候,就是报错 IDEA Access denied for user ''@'localhost' (using password: NO) 找了半天原因。 所以建议:laravel还是不要用laravel命令行启动项目 php artisan serve 假如更改了项目目录的配置文件就要重启命令行!!!切记!!!切
$form->text("name", "姓名") ->creationRules('required|unique:table', ['required' => '姓名不能为空','unique' => '姓名不能重复']) ->updateRules('required|unique:table,name,{{id}}', ['required' => '姓名不能为空','unique' =>
我在Laravel中创建了多重身份验证。当我使用用户登录时,在post login方法中调试时,在Auth::guard('user')之后- 如何解决?我是拉威尔的初学者。 谢谢!!! /路由/auth/user。php }); /路由/网络。php }); /app/Controllers/User/Auth/LoginController-@post登录 /应用程序/控制器/用户/家庭控制器
我设置了一个自定义的警卫和登录控制器 登录很好,但不知怎么的,它没有存储经过身份验证的用户 我读过这个"Auth::user()在Laravel 5.2中返回null" 并且这个"Auth::user()返回null" 但我认为我的问题与中间件无关 代码如下: 控制器: 型号: config/auth.php: 路线表: 我还尝试将此添加到控制器: 当我试图从视图访问Auth::user()时,它
我是新来的laravel。我试图登录用户,但我得到以下错误每次: SessionGuard.php第439行中的ErrorException:传递给Illumb\Auth\SessionGuard::login()的参数1必须是Illumb\Contracts\Auth\Authenticatable的实例,数组给定 这是我的表格: 这是我的路线: 和用户控制器中的登录方法: 谢谢你的帮助
我搜索并找到了如下各种结果:auth()- 但是,我的仍然不起作用。 在控制器中工作,但在模型中不工作。它返回。 代码是: 我尝试,它也返回。 任何想法?
我是一个新手,希望在筛选之前进行筛选,该筛选将检查我想要的内容,并将带错误或成功的重定向返回到相同的配置文件。 这是我的过滤前函数 这是我的路线 Route::组(数组) 路由::get('/user/{username}',数组('as'= 和我的ProfileController公共功能 所以我的问题是如何让这些重定向工作,我试图搜索谷歌等,我找不到任何答案。这是我在这里的第一篇文章,我的英语
import "os/user" user包允许通过名称或ID查询用户帐户。 type UnknownUserError func (e UnknownUserError) Error() string type UnknownUserIdError func (e UnknownUserIdError) Error() string type User func Current() (*User