0

I just checked using dd() that my variable $username and $password are not null. But why Auth::attempt($user) is always return error message Undefined index: password

LoginController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public function index()
    {
        return view('login/index', [
            'title' => 'LOGIN'
        ]);
    }

    public function authenticate(Request $request)
    {
        $hashed_password = hash(config('var.default_hash'), $request['password']);
        $request['password'] = $hashed_password;

        $request->validate([
            'username' => ['required'],
            'password' => ['required'],
        ]);

        $user = [
            'username' => $request['username'],
            'password_hash' => $request['password']
        ];

        if (Auth::attempt($user)) {
            $request->session()->regenerate();
            return redirect()->intended('/');
        }

        return back()->with('fail', 'Login fail');
    }
}

User.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends Model implements Authenticatable
{
    use HasFactory;
    public $timestamps = false;
    protected $fillable = ['name', 'username', 'password_hash', 'lang'];

    /**
     * The column name of the "remember me" token.
     *
     * @var string
     */
    protected $rememberTokenName = 'remember_token';

    /**
     * Get the name of the unique identifier for the user.
     *
     * @return string
     */
    public function getAuthIdentifierName()
    {
        return $this->getKeyName();
    }

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->{$this->getAuthIdentifierName()};
    }

    /**
     * Get the unique broadcast identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifierForBroadcasting()
    {
        return $this->getAuthIdentifier();
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->password_hash;
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string|null
     */
    public function getRememberToken()
    {
        if (!empty($this->getRememberTokenName())) {
            return (string) $this->{$this->getRememberTokenName()};
        }
    }

    /**
     * Set the token value for the "remember me" session.
     *
     * @param  string  $value
     * @return void
     */
    public function setRememberToken($value)
    {
        if (!empty($this->getRememberTokenName())) {
            $this->{$this->getRememberTokenName()} = $value;
        }
    }

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName()
    {
        return $this->rememberTokenName;
    }
}

2021_09_24_081907_create_users_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('username');
            $table->text('password_hash');
            $table->String('lang');
            $table->timestamp('created_at')->useCurrent();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
  • You need to send `password`, not `password_hash`, to `Auth::attempt` – aynber Sep 24 '21 at 15:08
  • if I change `password_hash` to `password` somehow its always return false – Bear Au Jus - ジュースとくま Sep 24 '21 at 15:11
  • 2
    By default, Laravel expects the password field to be named `password`. If you want to use `password_hash` instead, see https://stackoverflow.com/questions/39374472/laravel-how-can-i-change-the-default-auth-password-field-name on how to change the default field. – aynber Sep 24 '21 at 15:20
  • Accoring to [link](https://laravel.com/docs/8.x/authentication#authenticating-users) **You should not hash the incoming request's password value, since the framework will automatically hash the value before comparing it to the hashed password in the database.** My other mistakes is hashing the password before fitting them to `Auth`. I should keep them as raw text. – Bear Au Jus - ジュースとくま Sep 24 '21 at 16:25
  • That is correct. Store the hash, but send the plaintext to the authenticator. It will use the algorithm to check for you. – aynber Sep 24 '21 at 16:35

1 Answers1

0

I think you should create an array like this

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // Authentication was successful...
}

you need to change the username to email

then password_hash to password and you need to change your database user table.

https://laravel.com/docs/8.x/authentication#authenticating-users

Tirdad Abbasi
  • 707
  • 5
  • 17
  • If I change ``` $user = [ 'email' => $request['username'], 'password' => $request['password'] ]; ``` It will returns error like : ``` SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in 'where clause' (SQL: select * from `users` where `email` = qweqwe limit 1) ``` Because I don't have column called `email`. I mean.. do I really need to change database column name ? – Bear Au Jus - ジュースとくま Sep 24 '21 at 15:21