php - 如何最优获取id用户?

标签 php laravel laravel-5.5

我现在通过 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()之间的区别here .

关于php - 如何最优获取id用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48094166/

相关文章:

Laravel 5.5 设置迁移文件中整数字段的大小

PHP number_format 是否四舍五入?

javascript - 将数字从 HTML 传递给 JS 函数,在 JS 中变为 "undefined"。为什么?

php - 如何仅在 laravel 中使用 DATE 获取数据?

laravel - 如何更改 Laravel 中请求参数的值

php - 如果在登录页面(没有登录)中使用 Auth::logout() 会给出错误。拉拉维尔 5.5

java - 联系表格 7 wordpress 下拉菜单

php - 如何在提交表单后刷新网页

php - Laravel 通过数据透视表查询数据

php - 即使 postman 做对了,测试也无法正确断言请求