Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

grimdbu's avatar

Custom authentification query

How can I add DESC to the default login sql query? I mean on default is something like select * from users where name = user_name limit 1. How can I add select * from users where name = user_name ORDER BY id DESC limit 1?

0 likes
4 replies
martinbean's avatar

@victordbu The name column should contain unique values only. Authentication mechanisms should not rely on the order rows are stored in a database table.

Nospoon's avatar

You would need to implement a custom authentication user provider. Have a look at Illuminate\Auth\EloquentUserProvider, you can lift most of the logic from there. Then you need to replace the provider in your auth config. Have a look at the documentation on creating custom authentication guards and providers.

That being said though, this is an indication of a very bad authentication mechanism which you should change if possible.

grimdbu's avatar

If I add the orderby in the return in the Illuminate\Auth\EloquentUserProvider it works. How can I create a custom user provider to override only this method?

`public function retrieveByCredentials(array $credentials) { if (empty($credentials) || (count($credentials) === 1 && array_key_exists('password', $credentials))) { return; }

// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();

foreach ($credentials as $key => $value) {
    if (Str::contains($key, 'password')) {
        continue;
    }

    if (is_array($value) || $value instanceof Arrayable) {
        $query->whereIn($key, $value);
    } else {
        $query->where($key, $value);
    }
}

// return $query->first();

return $query->orderBy('id', 'desc')->first(); }`

Please or to participate in this conversation.