如何获得 id user optimaly?

How to get id user optimaly?

我现在通过 POST 请求从 html 表单获取数据。我的收件箱应用程序。我的代码有效但不是最佳代码。如果没有循环 foreach,我无法使用电子邮件获取 id 用户。如何在不循环的情况下获取用户 ID?

代码

public function send_message(Request $request)
    {
        if($request->isMethod('post'))
        {
            $to      = $request->to;
            $from    = Auth::user()->id;
            $subject = $request->subject;
            $message = $request->message;
            $to      = User::where('email', $to)->get()->toArray();

        foreach ($to as $value) {
            $to = $value['id'];
        }

        echo $to."<br>";
        echo $from."<br>";
        echo $subject."<br>";
        echo $message."<br>";

        Message::create(
            [
                'subject'=>$subject, 
                'message'=>$message, 
                'from'=>$from, 
                'to'=>$to
            ]
        );
    }
}

使用first()方法:

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

value()如果你只需要ID:

User::where('email', $to)->value('id');

first()get() 之间的区别解释为

使用first()方法获取唯一对象

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

对于 get(),您必须 select 集合中的第一个对象:

$to = User::where('email', $to)->get()[0]->id;

get() return 一个 集合 first() return 一个用户对象

很多方法

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

User::whereEmail('email')->first()->id;

你可以通过

获取当前认证用户的id
Auth::id();