Search code examples
phplaravellaravel-5laravel-5.1basic-authentication

Perform User Authentication if email provided exists in the database


In Laravel, is it possible to do a sign-in base on user email only - no password needed.


I'ved tried

public function postSignIn(){

      $validator = Validator::make(Input::only('email') , array(
        'email' => 'required',
      ));

      if ($validator->fails()) {
        return Redirect::to('/')->with('error', 'Please fill out your information ')->withErrors($validator)->withInput();
      }

      $email = strtolower(Input::get('email'));

      $auth = Auth::attempt(array('email' => $email ));

      if ($auth) {
        return Redirect::to('/dashboard')->with('success', 'Hi '. Auth::user()->name .'! You have been successfully logged in.');
      }

      else {
        return Redirect::to('/')->with('error', 'Username/Password Wrong')
          ->with('username', $username)
          ->withErrors($validator);
      }

I keep getting : Undefined index: password

Do I need to modify the any kind of Auth driver for this to work ?

Any hints/ suggestions on this will be much appreciated !


Solution

  • You can do something like this:

    public function postSignIn(){
    
          $validator = Validator::make(Input::only('email') , array(
            'email' => 'required',
          ));
    
          if ($validator->fails()) {
            return Redirect::to('/')->with('error', 'Please fill out your information ')->withErrors($validator)->withInput();
          }
    
          $email = strtolower(Input::get('email'));
    
          try{
              $user = User::where('email', $email)->firstOrFail();
              Auth::login($user);
    
              return Redirect::to('/dashboard')->with('success', 'Hi '. Auth::user()->name .'! You have been successfully logged in.');
          }
          catch(ModelNotFoundException $exception){
              return Redirect::to('/')->with('error', 'Username/Password Wrong')
                ->with('username', $username)
                ->withErrors($validator);
    
          }
    }
    

    You can check more info in here on how to manually login your users (you will have to scroll down a little bit)