Attempt to read property "needs_password" on null

Viewed 24

I created a password initial with email notification, now the problem here is when i click the link in the email i got an error. it says attempt to read property on null

this is my code by the way.

in my users table i add the

$table->boolean('needs_password')->default(false);

the User Model

    protected $table = 'users';
protected $fillable = [
    'name',
    'rec_id',
    'email',
    'join_date',
    'phone_number',
    'status',
    'role_name',
    'avatar',
    'needs_password',
    'password',
];

and my user controller after the admin create a user

        $url = URL::signedRoute('password-redirect');
        $pass  = Str::random(30);
        $image = time().'.'.$request->image->extension();
        $request->image->move(public_path('/assets/images/'), $image);

        $user = new User;
        $user->name             = $request->name;
        $user->email            = $request->email;
        $user->join_date        = $todayDate;
        $user->role_name        = $request->role_name;
        $user->status           = $request->status;
        $user->avatar           = $image;
        $user->password         = $pass;
        $user->save();
        DB::commit();            
        Mail::send('auth.mail', [ 'url' => $url], function($message) use ($request) {
            $message->from('noreply@taskproph.com');
            $message->to($request->email);
            $message->subject('Reset Password Notification');
        });

in my password controller

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

public function create(User $user)
{
    return view('auth.mail');
}

in my need_password middleware

    public function handle(Request $request, Closure $next)
{
   $user = $request->route('users');

   if ($user->needs_password) {
    
    return $next($request);

   }

   abort(400);
}

in my route

Route::controller(PasswordController::class)->group(function () {
Route::get('/password-redirect', 'create')->middleware('signed','needPass')->name('password-redirect');
Route::post('/create-password', 'store')->middleware('needPass')->name('create-password');

});

1 Answers
$user = $request->route('users');

if ($user->needs_password) {

These lines will fail in both of your routes, because the routes don't have a route parameter called "users". $user is always null for them. You're likely going to want to use $request->user() instead, and you're going to potentially want to handle cases where there's no currently logged-in user as well by checking that $request->user() returns something.

You've also got a logic error - your middleware (if it worked) is throwing an error 400 if the user has no password, but you're applying it to the create-password route. This means the user can't set a password!

These are probably the two routes that shouldn't have the needPass middleware applied.

Related