【问题标题】:Laravel check if user email verifiedLaravel 检查用户电子邮件是否已验证
【发布时间】:2020-08-25 08:04:20
【问题描述】:

您好,我想检查用户电子邮件是否仅在控制器的一个功能中验证,我不想在中间件或这样的路由中设置检查:

 public function __construct()
{
    $this->middleware('verified');
}

因为来宾可以访问控制器,所以控制器中只有一个功能(创建)需要验证电子邮件并登录用户我该怎么做,谢谢

        public function create()
    {

       // checking if authenticated but need to check if email verified also        
        if (Auth::check()) {

            // Get the currently authenticated user...
            $user = Auth::user();

            // get the list of states
            $states = State::orderBy('name', 'asc')->get();
            // get all cities by state_id
            $state_id  = '1';

            $cities = City::where('state_id', $state_id)->orderBy('name', 'asc')->get();

            return view('pages.create_product', ['user' => $user, 'states' => $states, 'cities' =>                     $cities]);
        } else {
            return redirect()->route('login');
        }
    }

【问题讨论】:

    标签: laravel


    【解决方案1】:

    我建议您在 web.php 路由文件中这样做:

    Route::get('example/create', ExampleController@create)->middleware('verified');
    

    或在控制器构造函数中执行此操作,但使用如下特定方法:

     public function __construct()
    {
        $this->middleware('verified')->only('create');
    }
    

    如果您真的想在控制器方法中执行此操作,可以使用此代码进行检查。

    $user = Auth::user();
    
    $user->hasVerifiedEmail();
    

    不要忘记在您的User 模型中包含MustVerifyEmail 接口。

    <?php
    
    namespace App;
    
    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    
    class User extends Authenticatable implements MustVerifyEmail
    {
        use Notifiable;
    
        // ...
    }
    

    【讨论】:

    • 谢谢你,我不想要前 2 个解决方案,因为那些会锁定整个控制器,我想使用第三个选项,但它给了我未定义的变量 '$user' 我如何定义 $user跨度>
    • @Zeoneline 不,前两个不会锁定整个控制器,它们用于特定的方法和路线。
    • 谢谢安迪先生,我很糟糕,我没有注意细节(->only('create');)你是对的,但是完美的详细答案所有 3 个答案都很好,谢谢你我从你那里学到了很多新东西:)
    • 还有一个问题我有一个 // 资源路由我如何在资源路由 web.php 到 ProductController 上的 create 方法应用你的第一个解决方案 Route::resources([ 'product' => 'ProductController ', 'user' => 'UserController', 'profile' => 'UserController', ]);
    • @Zeoneline 我认为您仍然可以将选项作为第二个参数传递Route::resources([ 'product' =&gt; 'ProductController', 'user' =&gt; 'UserController', 'profile' =&gt; 'UserController', ], ['only' =&gt; ['UserController.create']])-&gt;middleware('verified');
    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2019-09-04
    • 2019-03-12
    • 1970-01-01
    • 2021-03-21
    相关资源
    最近更新 更多