Skip to content
Advertisement

Laravel controller shows syntax error, unexpected variable “$user”, expecting “function” or “const”

I am creating a forgot password feature in my application and when creating my controller, I used this code:

$user = DB::table('users')->where('email', '=', $request->email)
->first();
//Check if the user exists
if (count($user) < 1) {
return redirect()->back()->withErrors(['email' => trans('User does not exist')]);
}

//Create Password Reset Token
DB::table('password_resets')->insert([
'email' => $request->email,
'token' => str_random(60),
'created_at' => Carbon::now()
]);
//Get the token just created above
$tokenData = DB::table('password_resets')
->where('email', $request->email)->first();

if ($this->sendResetEmail($request->email, $tokenData->token)) {
return redirect()->back()->with('status', trans('A reset link has been sent to your email address.'));
} else {
return redirect()->back()->withErrors(['error' => trans('A Network Error occurred. Please try again.')]);

But the first line gives an syntax error, unexpected variable "$user", expecting "function" or "const" error. Does anyone know what I am doing wrong?

Advertisement

Answer

public function yourFunctionName(){
  $user = DB::table('users')->where('email', '=', $request->email)
                ->first();
    //Check if the user exists
    if ($user->count()< 1) {
       return redirect()->back()->withErrors(['email' => trans('User does not exist')]);
    }
    
    //Create Password Reset Token
    DB::table('password_resets')->insert([
      'email' => $request->email,
      'token' => str_random(60),
      'created_at' => Carbon::now()
    ]);
    enter code here
    //Get the token just created above
    $tokenData = DB::table('password_resets')
                 ->where('email', $request->email)->first();
    
    if ($this->sendResetEmail($request->email, $tokenData->token)) {
        return redirect()->back()
                        ->with('status', trans('A reset link has been sent to your email 
                         address.'));
    } else {
       return redirect()->back() 
                        ->withErrors(['error' => trans('A Network Error occurred. Please 
                      try again.')]);
    }

Make Sure Your { } are correct..and the code inside a function,check ; are correct

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement