Undefined Variable : user - php

I am trying to send message with activation code. I have an registration form. The forms sends data to the controller and the controller saves the data into database . But somehow it fails to grab the $user variable after saving data into profiles table.
Here is my controller:
DB::transaction(function() use($first_name,$last_name,$email,
$password,$address,$phone,$country_id,$state,$city,
$zip_code,$skype,$birth_date,$code){
//add info to user table
$user = new User;
$user->username = $email;
$user->password = $password;
$user->email = $email;
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->active = 0;
$user->code = $code;
$user->save();
//Get the user ID ceated just now
$new_users = $new_user->id;
// add information to Profile table
$profile = new Profile;
$profile->user_id = $new_users;
$profile->phone = $phone;
$profile->address = $address;
$profile->country_id = 1;
$profile->state = $state;
$profile->skype = $skype;
$profile->city = $city;
$profile->zip_code = $zip_code;
$profile->birth_date = $birth_date;
$profile->timezone_id = 1;
$profile->save();
});//inside a transaction
if($user){
Mail::send('emails.welcome',
array('link'=> URL::route('account-activate', $code),'user'=>$user->first_name),
function($message) use ($user) {
$message->to($user->email , $user->user)->from('admin#spandango.net')->subject('Active your account !');
}
);
return Redirect::back()
->with('message' , 'Your account is created ! Please check you email to activate your account !'); }
return Redirect::to('/message');
I think my code is absolutely right. Can you please explain why it fails to define the $user variable ?

This is because of the scope of the $user variable. Define $user above DB::transaction(function() {});

Though defining
$user = false;
above
DB::transaction
might do the trick for now but I won't recommend it as a good practice the best solution would be to use the
Mail::send()
inside the Database transaction block and you might can improve your code as well and the above code should be
DB::transaction(function() use($first_name,$last_name,$email,
$password,$address,$phone,$country_id,$state,$city,
$zip_code,$skype,$birth_date,$code,$user){
//add info to user table
$user = new User;
$user->username = $email;
$user->password = $password;
$user->email = $email;
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->active = 0;
$user->code = $code;
$user->save();
//Get the user ID ceated just now
$new_users = $new_user->id;
// add information to Profile table
$profile = new Profile;
$profile->user_id = $new_users;
$profile->phone = $phone;
$profile->address = $address;
$profile->country_id = 1;
$profile->state = $state;
$profile->skype = $skype;
$profile->city = $city;
$profile->zip_code = $zip_code;
$profile->birth_date = $birth_date;
$profile->timezone_id = 1;
$profile->save();
if( !$profile || !$user )
{
return Redirect::back()
->with('message' , 'Your account is created ! Please check you email to activate your account !');
} else {
// Else commit the queries
Mail::send('emails.welcome',
array('link'=> URL::route('account-activate', $code),'user'=>$user->first_name),
function($message) use ($user) {
$message->to($user->email , $user->user)->from('admin#spandango.net')->subject('Active your account !');
}
);
}
});//inside a transaction

That is because $user is inside that DB transaction block; it goes out of scope with the closing brace. Define it above the transaction

Solution
Copy & Replace above.
$user = false;
DB::transaction(function() use($first_name,$last_name,$email,
$password,$address,$phone,$country_id,$state,$city,
$zip_code,$skype,$birth_date,$code,$user){
//add info to user table
$user = new User;
$user->username = $email;
$user->password = $password;
$user->email = $email;
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->active = 0;
$user->code = $code;
$user->save();
//Get the user ID ceated just now
$new_users = $new_user->id;
// add information to Profile table
$profile = new Profile;
$profile->user_id = $new_users;
$profile->phone = $phone;
$profile->address = $address;
$profile->country_id = 1;
$profile->state = $state;
$profile->skype = $skype;
$profile->city = $city;
$profile->zip_code = $zip_code;
$profile->birth_date = $birth_date;
$profile->timezone_id = 1;
$profile->save();
});//inside a transaction
if($user){
Mail::send('emails.welcome',
array('link'=> URL::route('account-activate', $code),'user'=>$user->first_name),
function($message) use ($user) {
$message->to($user->email , $user->user)->from('admin#spandango.net')->subject('Active your account !');
}
);
return Redirect::back()
->with('message' , 'Your account is created ! Please check you email to activate your account !'); }
return Redirect::to('/message');

Related

How to avoid duplicated records when concurrent requests make within a second in Laravel

please help me to find out the issue.
Sometimes (not always) my following code inserts two records in DB (into user table as well as profile table ),but i am checking before inserting that the "mobile_no" is already exist or not that to make unique mobile number based records.
static function postData($data) {
try {
if (isset($data['number'])) {
//exist
$exist = Profile::where('mobile_no', '=', $data['number'])->get();
//print_r($exist);
if (count($exist) > 0 ) {
$user = User::find($exist[0]['user_id']);
if (isset($data['last_name'])) {
$user->first_name = $data['first_name'];
}
if (isset($data['last_name'])) {
$user->last_name = $data['last_name'];
}
if (isset($data['email'])) {
$user->email = $data['email'];
}
$user->save();
$proid = $exist[0]['user_id'];
$profile_result = Profile::find($proid);
if (isset($data['number'])) {
$profile_result->mobile_no = $data['number'];
}
if (isset($data['birthday'])) {
$profile_result->dob = $data['birthday'];
}
$profile_result->save();
return $exist[0]['user_id'];
}else{
$user = new User();
if (isset($data['first_name'])) {
$user->first_name = $data['first_name'];
}
if (isset($data['last_name'])) {
$user->last_name = $data['last_name'];
}
$user->save();
$id = $user->id;
$profile = new Profile();
$profile->user_id = $id;
if (isset($data['mobile_number'])) {
$profile->mobile_no = $data['number'];
}
if (isset($data['birthday'])) {
$profile->dob = $data['birthday'];
}
$profile->save();
$proid = $profile->user_id;
$profile_result = $profile::where('user_id', '=', $proid)->get();
$user_result = $user::where('id', '=', $id)->get();
$output = array();
return (string) $id;
}
}
} catch (Exception $ex)
{
return $ex;
}
}
Using index UNIQUE for database and it will handle for you. Just remember to handle error properly when trying insert a duplicate key.

Laravel Eloquent Save Item Error?

When I try saving an item's to my database I get
Method Clients::__toString() must return a string value
Current code
$name = Input::get('email');
$client = Input::get('client');
$website = Input::get('website');
$userassign = Input::get('userassign');
$client = new Clients();
$client->name = $name;
$client->client = $client;
$client->website = $website;
$client->parent = $userassign;
$client->save();
Any ideas?
You're redefining $client.
$name = Input::get('email');
$clientInput = Input::get('client');
$website = Input::get('website');
$userassign = Input::get('userassign');
$client = new Clients();
$client->name = $name;
$client->client = $clientInput; //Here was your problem
$client->website = $website;
$client->parent = $userassign;
$client->save();

how to get primary key value of newly inserted user in zend

i have a problem on my project im currently working on and
this is my register controller
every time a user registers there will be a default image that will be displayed in their profile
public function registerAction()
{
$form = new Application_Form_Users();
$form->submit->setLabel('Register');
$this->view->form = $form ;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$id = $form->getValue('uid');
$firstname = $form->getValue('firstname');
$lastname = $form->getValue('lastname');
$email = $form->getValue('email');
$username = $form->getValue('username');
$password = $form->getValue('password');
$vpassword = $form->getValue('vpassword');
if ($password == $vpassword) {
$register = new Application_Model_DbTable_Users();
$password = md5($password);
$register->addUser($firstname , $lastname , $email , $username , $password );
if ($register) {
$register = new Application_Model_DbTable_Users();
$uid = $form->populate($register->getUser($id));
$addimg = new Application_Model_DbTable_Images();
$imagepath = APPLICATION_PATH.'/../public/upload/';
$addimg->addImage($uid , $imagepath);
}
$this->_helper->redirector('index');
} else {
$this->view->errorMessage = "Passwords don't match.";
}
} else {
$form->populate($formData);
}
}
}
this is my function to add default image path into my database
public function addImage($uid , $imgpath)
{
$data = array(
'uid' => $uid ,
'imgpath' => $imgpath ,
);
$this->insert($data);
}
but i got an error because my uid is null my question is how to get the value of uid in my users table, also users table and images table have a relation.
If you are using Zend_Db_Table then you can do something like this in addUser():
public function addUser($firstname , $lastname , $email , $username , $password ){
$user = $this->createRow();
$user->fname = $firstname;
$user->lname = $lastname;
...
$user->save();
return $user->id;
}
This will return you user id so you can do:
$id = $register->addUser($firstname , $lastname , $email , $username , $password );
and
$addimg->addImage($id , $imagepath); //$id, not $uid !
You can put a default value for $imgpath in your database for each new entry.
You can use the lastInsertId() function within the Zend_Db_Adapter class.
http://framework.zend.com/manual/1.12/en/zend.db.adapter.html#zend.db.adapter.write.lastinsertid
In your case it should be:
$this->getAdapter()->lastInsertId()
after your last line in the addImage method.
Warning: This does not work with all SQL adapters (like PostgreSQL)
From what i can get from your code, you're adding a new user, and then, adding an image related to his id.
$uid = $form->populate($register->getUser($id));
$addimg = new Application_Model_DbTable_Images();
$imagepath = APPLICATION_PATH.'/../public/upload/';
$addimg->addImage($uid , $imagepath);
And, you get an "error" because $uid is null. But $id shouldn't be null, and it should be the ID of the user you just added.
So you might try this and see if it works for you
$addimg->addImage($id , $imagepath);

Redbeanphp one to one relation

In my project have 2 entites in my db namely User and Account. One User has one account.User table has account_id field as foreign key to reference Account entity.
I am generating automaticly a new account for user. Everything gets created as I expect.But how can I reference an account for a parcticular user. Here is my registration script
public function register ($data = null)
{
if ($data != null) {
try {
$user = R::dispense('user');
$user->name = $data['name'];
$user->lastname = $data['last-name'];
$user->username = $data['username'];
$user->password = $data['password'];
$user->email = $data['email'];
$user->city = $data['city'];
$user->country = $data['country'];
//create account for user
$account = R::dispense('account');
$account->account_no = $this->genAccountNumber();
$account->money_sum = 0;
$user->account = $account;
$id = R::store($user);
return $id;
} catch (Exception $e) {
echo $e->getMessage;
}
}
}
Would be grateful for any help
You don't need to change anything - your way is correct. The line
$user->account = $account;
is the right way to do it - assuming you are running in fluid mode, your schema will be updated automatically to create the foreign key relationship for you this way.
To access the account, you just need to use $user->account.
echo $user->account;
will show you all the properties of the account bean.
Instead of giving account bean as foreign reference to user bean, just add account_id field as foreign key to user table.
public function register ($data = null){
if ($data != null) {
try {
$user = R::dispense('user');
$user->name = $data['name'];
$user->lastname = $data['last-name'];
$user->username = $data['username'];
$user->password = $data['password'];
$user->email = $data['email'];
$user->city = $data['city'];
$user->country = $data['country'];
//create account for user
$account = R::dispense('account');
$account->account_no = $this->genAccountNumber();
$account->money_sum = 0;
$account_id = R::store($account);
$user->account_id = $account_id; // this is the line you have to change
$id = R::store($user);
return $id;
} catch (Exception $e) {
echo $e->getMessage;
}
}}
And when loading a bean you can directly access account instance from user bean
(constraint being if there is a one-to-one or one-to-many maaping)
$account = $user->account;

How to manually create a user in Moodle?

I am trying to create an authentication plugin, but I am having problems when the user does not exist in the moodle database. Therefore I am trying to find a way to manually create a user.
I tried:
$user = new StdClass();
$user->username = $ucUser;
$user->auth = 'ucauth';
$user->firstname = "First";
$user->lastname = "Last";
$user->id = $DB->insert_record('user', $user);
But it didn't work... I got an insert error. What else do I need in the $user object?
User object should have the following values:
$user = new StdClass();
$user->auth = 'manual';
$user->confirmed = 1;
$user->mnethostid = 1;
$user->email = "email";
$user->username = "username";
$user->password = md5('password');
$user->lastname = "lastname";
$user->firstname = "firstname";
$user->id = $DB->insert_record('user', $user);
Please try this.
Well, I recommend you to use authenticate_user_login($username, null) this is going to give you an empty user, wich you can complete later on in the proccess. Then you can use complete_user_login($user); and if you want to send the user to the edit page something like
if (user_not_fully_set_up($USER)) {
$urltogo = $CFG->wwwroot.'/user/edit.php';
}else{
$urltogo = $CFG->wwwroot.'/';
}
redirect($urltogo);
I don't know exactly what are you trying to achieve. But I've made a plugin to connect with an external web service and it took me a while to figure out how to do it properly. I'm able to help you with anything you need.
There are some values that needs to be setted when creating a user manually. I was facing the same situation and ended up with this solution:
global $DB;
$user = new StdClass();
$user->email = strtolower('someemail'); //MOODLE requires lowercase
$user->username = strtolower('someusername');//MOODLE requires lowercase
$user->password = hash_internal_user_password('somepassword');
$user->lastname = 'somelastname';
$user->firstname = 'somename';
// These values are required.
// Default values are stored in moodle config files but... this is easier.
$user->auth = 'manual';
$user->confirmed = 1;
$user->mnethostid = 1;
$user->country = 'ES'; //Or another country
$user->lang = 'es'; //Or another country
$user->timecreated = time();
$user->maildisplay= 0;
$user->id = $DB->insert_record('user', $user); // returns new userid
If you prefer, you can retrieve the whole user's data:
$lastid = $DB->insert_record('user', $user);
$user2 = get_complete_user_data('id', $lastid);

Categories