2

I now get data from html form with POST request. My app for inboxing. My code working but code of not optimaly. I can't get id user using email without loop foreach. How I can get id user without loop?

Code

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
            ]
        );
    }
}
Andreas Hunter
  • 4,504
  • 11
  • 65
  • 125

3 Answers3

3

Use the first() method:

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

Or value() if you just need ID:

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

The difference between first() and get() is explained here.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
2

Use first() method to get unique object

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

With get() you have to select the first object in the collection:

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

get() return a collection while first() return one User object

YouneL
  • 8,152
  • 2
  • 28
  • 50
2

a lot of ways

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

OR

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

you can get the id of current authenticated user via

Auth::id();
Mahdi Younesi
  • 6,889
  • 2
  • 20
  • 51