Reputation: 5024
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?
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
]
);
}
}
Upvotes: 2
Views: 68
Reputation: 8371
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
Upvotes: 2
Reputation: 7509
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();
Upvotes: 2
Reputation: 163898
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.
Upvotes: 3