Skip to content
Advertisement

Laravel 5 – get ID by other field properly

I want to get the ID of a user in a middleware by searching with his email. I thought about doing it like this in one of two ways.

First, creating a function in the model User:

public function getIdByMail($query, $q) {
    return $query->select('id')->where('email', $q);
}

Second, using this function in my middleware

use AppUser;
...
$user = User::getIdByMail($user_id);

And it doesn’t work, nor am I even sure it’s the right way…

Advertisement

Answer

This should do it. No need for extra methods in model. Eloquent makes everything pretty simple.

$id = User::where('email', $email)->first()->id;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement