Call to a member function hasVerifiedEmail() on null

Viewed 3183

I am using Laravel 7 and I am trying to verify my email I have followed all the steps mentioned in the documentation but I am still getting this error please me to resolve this error, Thanks

enter image description here

I added the user model code here

<?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;

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

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

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

here is web.php

Auth::routes(['verify'=> true]);

Route::prefix('student')->middleware(['auth', 'verified'])->group(function () {
    Route::get('dashboard', 'StudentController@dashboard');
});
3 Answers

The $request is sending a null value because you need to be logged in (authenticated) in order to get an instance of the $user

Make sure you have a middleware of auth on your route

Assigning Middleware To Routes:

Route::get('admin/profile', function () {
    //
})->middleware('auth');

or Middleware Groups:

Route::group(['middleware' => ['auth']], function () {
    Route::get('admin/profile', function(){
        //your function here
    });
});

Laravel Official Doc

only users logged could acheave the function hasVerifiedEmail() , because of that you get the response : Call to a member function hasVerifiedEmail() on null , to fix that issue you have to customise show function in VerificationController.php

public function show(Request $request)
    {
//login user
        if (auth()->user())
        {
            return $request->user()->hasVerifiedEmail()
                ? redirect($this->redirectPath())
                : view('auth.verify');
        }
//guest
        else
        {
            return $request->user()
                ? redirect($this->redirectPath())
                : redirect('/login');
        }

    }
Related