【问题标题】:How to get id user optimaly?如何优化 id 用户?
【发布时间】:2018-06-14 02:50:54
【问题描述】:

我现在通过 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
            ]
        );
    }
}

【问题讨论】:

    标签: php laravel laravel-5.5


    【解决方案1】:

    使用first() 方法:

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

    或者value()如果你只需要ID:

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

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

    【讨论】:

      【解决方案2】:

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

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

      使用get(),您必须选择集合中的第一个对象:

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

      get() 返回一个 collectionfirst() 返回一个用户对象

      【讨论】:

        【解决方案3】:

        很多方法

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

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

        你可以通过

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-11-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多