I'm trying to find a user form a database with 'email' = $email and send them an email. When I try to echo the $user, I receive an error that it's not a string.
public function sendEmail($user)
{
Mail::to($user['email'])->Send(new VerifyEmail($user));
}
public function verifyEmail($email)
{
$user = User::where('email',$email);
$this->sendEmail($user ); //mail won't send
return view('auth.email.verifyemail')->with('email', $email);
}
Please help, thank you!
Your code has a few more issues than not being able to find the user, but let's address this first.
Explanation
Calling the where() method on the User::class is returning an instance of Illuminate\Database\Query\Builder and not the record that you are looking for.
To get a collection of records you can call fluently the get() method or in your case you can just get the first result by calling first().
More on the topic: Retrieving Single Models / Aggregates
Solution
$user = User::where('email', '=', $email)->first();
if(!$user) {
// handle the case if no user is found
}
echo $user->email // access the user's email address
Then you can call your sendmail method or whatever you need and pass the $user instance like this $this->sendmail($user)
$thisUser has only a query. You need to execute it to get the user. Try to get the first record:
$thisUser = User::where('email',$email)->first();
Related
Developing an API where at the start of every request, the provided API key is used to obtain the Account object which is associated with the request.
$account = $em->getRepository(Entity\Account\Account::class)
->findOneBy(['mainKey'=>$request->getHeaderLine('X-API-Key')]);
This Account entity contains a User's ArrayCollection where each of the User entities contains an username property which is unique for a given Account.
Given the username, how can I obtain the User entity? I can do something like the following, however, feel I should be doing differently.
$user = $em->getRepository(Entity\Account\User::class)
->findOneBy(['accountId'=>$account->getId(), 'username'=>'John.Doe']);
Thanks,
PS. I assume that findOneBy() is using a prepared statement behind the scenes and isn't subject to SQL injection, right?
PSS. I just assumed that an ArrayCollection holds a group of objects, but looking at some of the docs, am now not certain.
If Account is related to User (I suppose it is one-to-one), then Account should have $user property defined. And you can access it kinda:
$user = $account->getUser();
Where getUser is:
public function getUser()
{
return $this->user;
}
Both of these approaches seem to work:
$criteria = \Doctrine\Common\Collections\Criteria::create()
->where(\Doctrine\Common\Collections\Criteria::expr()->eq("username", $username));
$user = $users->matching($criteria)->current();
$expr = new \Doctrine\Common\Collections\Expr\Comparison('username', '=', $username);
$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($expr);
$user = $users->matching($criteria)->current();
I'm using Laravel 5.5.
I read about this and know this function and it works makeVisible
$hidden = ['password', 'remember_token', 'email'];
I can display email using
$profile = auth()->user()->find($request->user()->id);
$profile->makeVisible(['email']);
On the frontend email is displayed. But it not works on many results like
// Get all users
$users = User::with('role', 'level')->makeVisible(['email'])->paginate(10); // Doesn't work
Also try this method from Laracasts toJson it works but I can't do it using paginate. Can you provide other methods or how to solve this? My aim is to display email column that is hidden. Thanks.
Another, possible easier solution depending on your requirements, is to call makeVisible on the collection:
// Get all users
$users = User::with('role', 'level')->paginate(10)->makeVisible(['email']);
You can also use this with find or get:
$profile = auth()->user()->find($request->user()->id)->makeVisible(['email']);
I solve this using this method.
Users.php on model
public function toArray()
{
// Only hide email if `guest` or not an `admin`
if (auth()->check() && auth()->user()->isAdmin()) {
$this->setAttributeVisibility();
}
return parent::toArray();
}
public function setAttributeVisibility()
{
$this->makeVisible(array_merge($this->fillable, $this->appends, ['enter_relationship_or_other_needed_data']));
}
and on controller just a simple
return User::with('role', 'level')->paginate(10);
I've read where pagination comes from toArray before creating pagination. Thanks for all your help. Also helps
You can use this:
$paginator = User::with('role', 'level')->paginate($pageSize);
$data = $pagination->getCollection();
$data->each(function ($item) {
$item->setHidden([])->setVisible(['email']);
});
$paginator->setCollection($data);
return $paginator;
You can try to use this approach. Using API Resources.
API Resources lets you format the data the way you want. You can create multiple Resource object to format in different ways your collections.
Set visible your parameter (in this case email) and when you need to return that item you can use a different Resource object that returns that elemement.
So when no need for email:
$users = User::with('role', 'level')->paginate(10);
return UserWithoutEmail::collection($users);
when email is needed:
$users = User::with('role', 'level')->paginate(10);
return UserWithEmail::collection($users);
I'm trying save user IP adress after login on website. I'm using laravel 5.2 framework. I got user table and login_ip row. My code looks like that:
$user = User::where('login_ip', Request::getClientIp());
$user->save();
But it does not saving. What i'm doing wrong? Sorry for my bad english :)
If you want to save IP for current user, you can do this:
auth()->user()->update(['login_ip' => Request::getClientIp()]);
This will not create additional query as code in shoieb0101, Amit and Ronald answers.
Don't forget to add login_ip to the $fillable array in User model:
protected $fillable = ['login_ip'];
If you want to save IP for only logged in users and ignore guests, you can do a check:
!auth()->check() ? : auth()->user()->update(['login_ip' => Request::getClientIp()]);
Try
$user = User::find(auth()->user()->id);
$user->login_ip = Request::getClientIp();
$user->save();
//assuming $userid is also requested
$user = User::where('id', $userid);
$user->login_ip = Request::getClientIp();
$user->save();
You can try it as:
auth()->user()->login_ip = Request::getClientIp();
auth()->user()->save();
OR
auth()->user()->save(['login_ip' => Request::getClientIp()]);
Note - It will update the user's login_ip in single query.
You dont have to get logged user form db, all info about your user you have in Auth::user() so:
Auth::user()->login_ip = Request::getClientIp();
Auth::user()->save();
or
Auth::user()->login_ip = $request->ip();
Auth::user()->save();
but you need to have Request $request as parameter of your method.
I am probably stating the obvious, but your first line...
$user = User::where('login_ip', Request::getClientIp());
... returns an Eloquent query builder, right?
So, a save() on this will never work?
$user = User::where('login_ip', Request::getClientIp())->first();
... will return an actual User (if in the DB), which makes save() also possible.
Or did you make a typo in your OP?
I am writing a Symfony3 appusing Doctrine ORM.
SO what i am trying to do is to find if a given email address exists in a table (every email is unique). so i have a user repository with some attributes I can easily persist data to the db but failing to retrive data.
/**
* #param $email
*/
public function findUserByEmail($email)
{
$user = $this->getDoctrine()
->getRepository('TestBundle:TestUser')
->find($email);
if (!$user) {
echo 'Error';die();
}
}
I know the var passed to the function contains a email string, but what i get in return is error and when i var_dump $user before the if statment i get null.
I followed the Symfony docs
Your User probably has a separate primary key field. the find() method on a repo only retrieves by primary key.
Repositories use __call to dynamically process findBy* and findOneBy* methods, so you could call it like this:
$repo = $this->getDoctrine()->getRepository('TestBundle:TestUser');
// magic find method
$user = $repo->findOneByEmail($email);
// explicit find method
$user = $repo->findOneBy(['email' => $email]);
// custom QueryBuilder
$user = $repo->createQueryBuilder('user')
->where('user.email = :email')
->setParameter('email', $email)
->getQuery()
->getSingleResult();
BTW: If you are validating this for a submitted form, there is a contraint that does this check for you: UniqueEntity
I think the problem is because you forgot to call getManager().
So the code would be:
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('TestBundle:TestUser')->findOneBy(['email' => $email]);
Hope it would help you!
I've set up a log in process where a verification code is generated, and when successful, is then removed. However, i want to make sure that if there's multiple verification codes for the same user, upon log in success, delete all records for that user.
Here's my code
if ($model->validate() && $model->login()) {
//delete this verification code
$verificationCode->delete();
//delete all existing codes for user_id
VerificationCode::model()->deleteAll('user_id',$user->id);
Yii::app()->user->setReturnUrl(array('/system/admin/'));
$this->redirect(Yii::app()->user->returnUrl);
}
However, this seems to just delete all the records, regardless on different user_id's in table. Can anyone see where I'm going wrong?
If you want to delete record with specified attributes, the cleanest way for this is to use deleteAllByAttributes():
VerificationCode::model()->deleteAllByAttributes(['user_id' => $user->id]);
Seems you call the function delete() in wrong way ... try passing value this way
VerificationCode::model()->deleteAll('user_id = :user_id', array(':user_id' => $user->id));
For Yii2, the documented way is to use the function deleteAll().
I normally pass the arguments as an array, like so:
VerificationCode::deleteAll(['user_id' => $user->id]);
Also, you can use the afterDelete method, to make sure that everytime or everywhere someone deletes one verificationCode, your application will also delete every userVerificationCode. Put this in your verificationCode model class:
protected function afterDelete()
{
parent::afterDelete();
VerificationCode::model()->deleteAll('user_id = :user:id',[':user_id' =>$this->user_id]);
//... any other logic here
}
You can use below method for deleting all user_id entry from database:
$criteria = new CDbCriteria;
// secure way for add a new condition
$criteria->condition = "user_id = :user_id ";
$criteria->params[":user_id"] = $user->id;
// remove user related all entry from database
$model = VerificationCode::model()->deleteAll($criteria);
or you can use another method directly in controller action
VerificationCode::model()->deleteAll("user_id= :user_id", [":user_id"
=>$user->id]);
use below method for redirecting a URL
$this->c()->redirect(Yii::app()->createUrl('/system/admin/'));