我现在通过 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/