when you dd($user) you should be able to see the email address?
Accessing properties on a Collection right after fetching it from the Database
So I am trying to fetch a user and then immediately use the data from the object. But, I am not sure how to do that because I keep getting an error telling me I am trying to access a property that doesn't exist.
What I have is a simple contact form where a user contacts another user through the application. I don't want to publicly display email addresses so when the user submits the contact form, I am doing an ajax call passing in the username of the owner of the asset and then looking up that user to get the email address with the username, then getting the email address from that user.
public function contact(ContactSellerRequest $request){
$input = $request->all();
try{
$user = User::where('username', $input['username'])->get();
//dd($user); Good here with the user object, but, I cannot access $user->email
} catch (ModelNotFoundException $e) {
// Do something here later
}
if($user){
$data = [];
$data['message'] = $input['message'];
$message = new Messages($user->email, $user->username);
$message->contactSeller($data);
return Response::json(['sent' => true, 'data' => 'Su Correro ha sido Mandado Exitosamente.'], 200);
}
return Response::json('error', 400);
}
Really I just need to know a way I can grab a user for the db and then use their email address immediatly within the same method. I appreciate any insight and you guys here are awesome!
Aah I see the problem! Laravel returns a collection when you use get() on a query. If you only want one result you need to use the first() method
// Returns collection (multiple users or array of users)
$users = User::where('username', $input['username'])->get();
// Returns one user
$user = User::where('username', $input['username'])->first();
So you need to update get to first and it should work ;)
Please or to participate in this conversation.