简体   繁体   中英

Can't authenticate with created model on Laravel 5.1

In code with the comment "THIS IS NOT WORKING", I can't authorize.

I get user object and use Auth::login($user) but it doesn't work.

User in this moment creates in database.

  public function login(Request $request) 
  {
    if(Auth::check()) {
      return redirect('home');
    }
    if($request->isMethod('post')) {
      if($request->has('username') && $request->has('password')) {
        $inputs = $request->except('_token');
        if(!Auth::attempt(['username' => $inputs['username'], 'password' => $inputs['password']])) {
          $user = $this->registerUser($inputs);
          if($user) {
            Auth::login($user);
          }
        } 
      } 
      return (Auth::check()) ? redirect()->route('home') : redirect()->back()->with('form_error', true);
    }
    return view('pages.auth.login');
  }

User.php maybe here is something wrong?

namespace App\Models\system;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;
    protected $primaryKey = 'uid';
    protected $table = 'eltk.dbo.system_users';
    protected $guarded = [];
    protected $hidden = ['password', 'remember_token'];
}

Let's start step by step.

  1. Why did you create user on a method where you need to handle just login logic?
  2. What's the name of your database? Is it eltk or dbo or what? Define it in config/database.php under 'database' or in .env and use in model just table name, not name of the whole table, is not necessary.
  3. In login method you need something like this:

     public function processLogin(Request $request){ if(Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'), 'active' => 1])){ return redirect('/'); }else{ return redirect('login')->withMessage('User with this email and/or password does not exist or your account is not active.'); } 

    }

And btw, when you in if-else statement login user afterward you need to redirect him on some route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM