简体   繁体   中英

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 App\User;
...
$user = User::getIdByMail($user_id);

And it doesn't work, nor am I even sure it's the right way...

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

$id = User::where('email', $email)->first()->id;

To interact with the DB only from the model than

$post= \App\Models\Category::where([
        ['name' , $name]])->first()->id;

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