How to solve Trying to get property of non-object in Laravel

I'm a beginner web developer I'm trying to write a condition that will be fulfilled depending on what data the user will send Condition if fulfilled by one hundred percent But the condition else produces an error with the following text

Trying to get property 'unique_id' of non-object

If someone have info how to solv this problem I will be grateful

This is my code from controller

public function checkRestorePassword(Request $request)
{
    $result['success'] = false;

    $rules = [
        'unique_id' => 'required',
    ];
    $validation = Validator::make($request->all(), $rules);
    if (empty($validation))
    {
        $result['error'] = "Enter the code that was sent to you by mail.";
        return response()->json($result, 422);
    }
    $user = User::where('unique_id', $request->uniqueId)->first();
    if ($user->unique_id === $request->uniqueId)
    {
        $result['success'] = 'Access to your personal account successfully restored. Please change your password.';
        return response()->json($result, 200);
    }
    else
    {
        $result['success'] = false;
        return response()->json($result, 422);
    }
}

Upvotes: 0

Views: 818

Answers (1)

Andy Song
Andy Song

Reputation: 4684

I think it's because $user is returning null.

so do this

if (!is_null($user) && $user->unique_id === $request->uniqueId)

Upvotes: 1

Related Questions