How to input external variable as in laravel mailer in users controller? - php

I have a function in user controller in laravel that allows users to enter their name and email in a form and send an email to administrator. But when I try to the variable containing them in the MailTo function, it gives error. Here is my code:
public function send_email_contact_us(){
$name = Input::get('name');
$email = Input::get('email');
$message_contact = Input::get('message');
$sender_email = Input::get('email');
$sender_name = Input::get('name');
$validator = Validator::make(
array(
'name' => $name,
'email' => $email
), array(
'name' => 'required',
'email' => 'required',
)
);
if ($validator->fails())
{
$error_messages = $validator->messages()->all();
return Redirect::back()->with('flash_errors',"Message not sent, please try again.");
}
else
{
$data=array("name"=>$name,"email"=>$email,"message_contact"=>$message_contact);
Mail::send('emails.contactus',$data, function($message)
{
$message->from($sender_email, $sender_name); // THIS GIVES ERROR
$message->to("admin#admin.com")->subject('Contact Us');
});
return Redirect::back()->with('flash_success',"Message sent successfully.");
}
}
Any help would be highly appreciated.

change to this
Mail::send('emails.contactus',$data, function($message) use($sender_email,$sender_name)
{
$message->from($sender_email, $sender_name);
$message->to("admin#admin.com")->subject('Contact Us');
});
To use external variables in a closure you have to import the variable into the closure by using the use keyword

Related

email function not passing variable to view

i want to pass a variable $data to my email views but i get undefined variable.
this is the controller method
public function broadcastemail(Request $request)
{
$this->validate($request,
[
'subject' => 'required',
'emailMessage' => 'required'
]);
$emailMessage = $request->emailMessage;
$data['emailMessage'] = $emailMessage;
Mail::send('backend.user.emailMessage', $data, function($message)
{
$subject = request()->subject;
$user = User::find('31');
$email = $user->email;
$name = $user->first_name;
$message->to($email, $name)->subject($subject)->with('data',$data);
});
//Mail::to($to)->send($data);
//send_email($to, $name, $subject, $message);
return back()->withSuccess('Mail Sent Successfuly');
}
and this is my view
<p>{{$data['emailMessage']}}</p>
try to use {{ $emailMessage }} instead of {{$data['emailMessage']}} in your view and use keyword for using inside the closure function of MAIL

How can I sent an activation link to my registered user in Laravel?

I'm trying to sent an activation link to my registered user.
Here is my postRegister() function
public function postRegister(){
$validator = Validator::make( Input::all(), array(
'name' => 'required|min:2|max:20',
'email' =>'required|max:50|email|unique:users',
'username' =>'required|max:20|min:3|unique:users',
));
if ($validator->fails()) {
return Redirect::to('/')
->with('error_register','Something Wrong')
->withErrors($validator)
->withInput();
}
$user = new User;
$user->name = Input::get('name');
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->code = str_random(60);
$user->password = '';
$user->active = 0;
$user->type = 'Aveniros';
$user->save();
// Email
Mail::send('emails.activation', array(
'username'=>$user->username,
'name'=>$user->name,
'code'=>$user->code,
'email'=>$user->email
),
function($message){
$message->from(env('MAIL_USERNAME'),'Aveniros Site');
$message->to( $user->email, $user->name )->subject(' Aveniros Site Activation ');
});
return Redirect::to('/')
->with('success',' Your Account has been created ! <small> Email has been sent to set-password, and activation.</small>');
}
}
Bug
$message->to( $user->email, $user->name )->subject(' Aveniros Site Activation ');
Error
Undefined variable: user
How can I use/call my $user variable ?
I thought we can access them after the $user->save(); - right ?
But clearly, I can't. Please correct me if I am wrong.
I figured out my own answer, I just realize that I need to add use ($user)
into this line function($message) use ($user){
Final Mail::Sent() should look like this
// Email
Mail::send('emails.activation', array(
'username'=>$user->username,
'name'=>$user->name,
'code'=>$user->code,
'email'=>$user->email
),
function($message) use ($user){
$message->from(env('MAIL_USERNAME'),'Aveniros Site');
$message->to( $user->email, $user->name )->subject(' Aveniros Site Activation ');
});

Unexpected T Variable Laravel

I'm getting an error on the following on:
$user->email = Input::get('email');
I'm really unsure what is wrong with the code, it seems perfectly fine. I looked up t variable errors, simply involve missing a bracket or semi colon. But as far as I'm aware it seems fine.
If anyone could help me out, that would be great.
If there is any other code, could you list it as a comment and i'll happily add it.
Thanks!
public function doRegister()
{
$rules = array(
'name' => 'required|min:3', // name
'email' => 'required|email', // make sure the email is an actual email
'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
// validation not successful, send back to form
Redirect::back()->withErrors;
} else {
$user = Input::all();
User::addNewUser();
if (Auth::attempt($user)) {
return Redirect::to('member');
}
}
}
User model
public static function addNewUser()
{
$user = new User;
$user->name     = Input::get('name');
$user->email    = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
}
It's because of $user->save; it's a method not a property and it should be called like
$user->save();
Instead of
$user->save;
Update : Also, it's U not u
$user = new user;
should be
$user = new User; // capital U
Also, after if ($validator->fails())
Redirect::back()->withErrors;
should be
return Redirect::back()->withErrors($validator);
Update : So, after fixing 3 errors (so far), your full code should be
public function doRegister()
{
$rules = array(
'name' => 'required|min:3',
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
return Redirect::back()->withErrors($validator);
}
else {
$user = new User;
$user->name =Input::get('name');
$user->email= Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
if (Auth::attempt($user)) {
return Redirect::to('member');
}
}
}

how to check if a user email already exist

In laravel, when a new user is registering to my site and the email they use already exist in the database. how can tell the user that the email already exist ?. I am new to laravel framework. A sample code would be nice too.
The validation feature built into Laravel lets you check lots of things, including if a value already exists in the database. Here's an overly simplified version of what you need. In reality you'd probably want to redirect back to the view with the form and show some error messages.
// Get the value from the form
$input['email'] = Input::get('email');
// Must not already exist in the `email` column of `users` table
$rules = array('email' => 'unique:users,email');
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
echo 'That email address is already registered. You sure you don\'t have an account?';
}
else {
// Register the new user or whatever.
}
);
Laravel has built-in human readable error messages for all its validation. You can get an array of the these messages via: $validator->messages();
You can learn more about validation and what all you can do with it in the Laravel Docs.
Basic Usage Of Unique Rule
'email' => 'unique:users'
Specifying A Custom Column Name
'email' => 'unique:users,email_address'
Forcing A Unique Rule To Ignore A Given ID
'email' => 'unique:users,email_address,10'
Adding Additional Where Clauses
You may also specify more conditions that will be added as "where" clauses to the query:
'email' => 'unique:users,email_address,NULL,id,account_id,1'
The above is from the documentation of Laravel
You could add:
public static $rules = [
'email' => 'unique:users,email'
];
You can add more rules to the $rules like:
public static $rules = [
'email' => 'required|unique:users,email'
];
It will automatically produce the error messages
and add:
public static function isValid($data)
{
$validation = Validator::make($data, static::$rules);
if ($validation->passes())
{
return true;
}
static::$errors = $validation->messages();
return false;
}
to the model User.php
Then in the function you're using to register, you could add:
if ( ! User::isValid(Input::all()))
{
return Redirect::back()->withInput()->withErrors(User::$errors);
}
if(sizeof(Users::where('email','=',Input::get('email'))->get()) > 0) return 'Error : User email exists';
The great resource is only Laravel Documentation #
enter link description here
I also did like below when integrating user management system
$user = Input::get('username');
$email = Input::get('email');
$validator = Validator::make(
array(
'username' => $user,
'email' => $email
),
array(
'username' => 'required',
'email' => 'required|email|unique:users'
)
);
if ($validator->fails())
{
// The given data did not pass validation
echo 'invalid credentials;';
// we can also return same page and then displaying in Bootstap Warning Well
}
else {
// Register the new user or whatever.
$user = new User;
$user->email = Input::get('email');
$user->username = Input::get('username');
$user->password = Hash::make(Input::get('password'));
$user->save();
$theEmail = Input::get('email');
// passing data to thanks view
return View::make('thanks')->With('displayEmail', $theEmail);
}
public function userSignup(Request $request, User $data){
# check user if match with database user
$users = User::where('email', $request->email)->get();
# check if email is more than 1
if(sizeof($users) > 0){
# tell user not to duplicate same email
$msg = 'This user already signed up !';
Session::flash('userExistError', $msg);
return back();
}
// create new files
$data = new User;
$data->name = $request->name;
$data->email = $request->email;
$data->password = md5($request->password);
$data->save();
//return back
Session::flash('status', 'Thanks, you have successfully signup');
Session::flash('name', $request->name);
# after every logic redirect back
return back();
}
I think when u try something like this you earn a smooth check using Model
We can use the Validator.
In your Controller.
$validator = $request->validate([
'name' => 'required',
'phone' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
]);
In View
#error('email') <span class="text-danger error">{{ $message }}</span>#enderror
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'email' => 'required|min:4|email|unique:users',
'password' => 'required',
]);
Try This

Unique email check in zend framework is not working properly

I am working on a project based on Zend framework. In user registration I have to check for unique email. My code is working fine when I register a user for the first time, but when I try to update the user information and press the update button, it gives the error message:
Email already taken
Please help me to solve this problem. My code is attached below:
$this->addElement('text', 'email', array(
'label' => 'Your email address:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
array('Db_NoRecordExists', true, array(
'table' => 'users',
'field' => 'email',
'messages' => array(
'recordFound' => 'Email already taken'
)
)
)
)
));
I have changed my controller to this:
public function addAction()
{
$modelUsers = new Model_Users();
$userId = $this->_getParam('userId');
$form = $this->_getAddForm();
if ($userId) {
$populateData = array();
$user = $modelUsers->fetch($userId);
if ($user instanceof Model_User) {
$populateData = $user->toArray();
}
$form->populate($populateData);
}
$request = $this->getRequest();
if ($request->isPost()) {
$email = $this->getRequest()->getParam('email');
if (strtolower(trim($email)) == $modelUsers->fetchByEmail($email)) {
// change $this->_user->getAccount()->getEmail() to retrieve the user's current email address
// remove validator from form
$form->getElement('email')->removeValidator('Db_NoRecordExists');
}
$post = $request->getPost();
if ($form->isValid($post)) {
$values = $form->getValidValues($post);
$data = array(
'firstName' => $values['firstName'],
'userTypeId' => 2,
'lastName' => $values['lastName'],
'email' => $values['email'],
'userName' => $values['userName'],
'password' => $values['password'],
'role' => $values['role']
);
if ($userId) {
$user = $modelUsers->fetch($userId);
if ($user instanceof Model_User) {
$user->setFromArray($data);
$success = $user->save();
if ($success) {
echo Zend_Json::encode(array('status' => self::STATUS_SUCCESS, 'message' => 'Successfully updated the user!'));
exit;
}
}
} else {
$user = $modelUsers->createRow($data);
$success = $user->save();
if ($success) {
echo Zend_Json::encode(array('status' => self::STATUS_SUCCESS, 'message' => 'Successfully added the user!'));
exit;
}
}
echo Zend_Json::encode(array('status' => self::STATUS_FAILED, 'message' => 'user not added'));
exit;
} else {
$errors = array();
$errors = $form->errors();
echo Zend_Json::encode(array('status' => self::STATUS_ERROR, 'data' => $errors));
exit;
}
}
$this->view->form = $form;
$this->_helper->layout->disableLayout();
}
Model:
public function fetchByEmail($email)
{
$email=fetchOne('SELECT email FROM users WHERE email = $email');
//$select->where('email=?',$email) ;
//$student = $this->fetchRow($select);
return $email;
}
But still this is not working
One simple way you can solve this problem is to remove the validator from that form element when the form is being edited. You may also want to keep the validator if they are attempting to change their email address since they shouldn't be able to change their email to one that already exists in the database.
Leave the validator in your Zend_Form class, add this code only when a user is being edited.
if ($this->getRequest->isPost()) {
$email = $this->getRequest()->getParam('email'); // get email from form
// if email address has not changed, remove validator from form
if (strtolower(trim($email)) == $this->_user->getAccount()->getEmail()) {
// change $this->_user->getAccount()->getEmail() to retrieve the user's current email address
// remove validator from form
$form->getElement('email')->removeValidator('Db_NoRecordExists');
}
// validate form
if ($form->isValid($this->getRequest()->getPost()) {
//...
}
}
So what you are doing is removing the Db_NoRecordExists validator from the form element when the form is being edited, and only if they are not attempting to change their email address if they are allowed to do so.
It will give you allways this error because you are using validation , that email is present in DB table or not.
But the email is existing in database that's why it is giving error.
Remove this validation , it will help you.
if(isset($_SESSION['session_id']))
{
// code for update query
}
else
{
// code for insert query
}

Categories