I have the following code in a seeder:
public function develop_run()
{
echo "Running ParentUsersTableSeeder\r\n";
DB::table('parent_users')->truncate();
$faker = Factory::create('en_AU');
$rand = rand(100, 300);
for ($i = 0; $i < $rand; $i++) {
$email = $faker->email;
// Create the new user
$parentUser = ParentUser::create([
'first_name' => $faker->firstName,
'last_name' => $faker->lastName,
'email' => $email,
'country_id' => rand(1, 209),
'last_access_at' => Carbon::today(),
]);
}
}
I cannot understand why the seed fails (at the $parentUser = step) with:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Type error: Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in /home/vagrant/src/facultyenews/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 681
The items each individually show correctly if I dd() them. I have other seeds with the same syntax working perfectly, so I assume it is a simple screw up, but I cannot find it.
Any ideas welcome.
Results of dd():
dd($email);
"xlueilwitz#yahoo.com"
dd($faker->firstName);
"Seamus"
dd($faker->firstName);
"Jones"
From another seeder in the same project, this works:
private function createRows($school, $role) {
$faker = Factory::create('en_AU');
$firstName = $faker->firstName;
$lastName = $faker->lastName;
$email = $firstName.'_'.$lastName.'#'.$school->website;
// Preset Users and Schools
$school_user = SchoolUser::create([
'first_name' => $firstName,
'last_name' => $lastName,
'email' => $email,
'password' => bcrypt('a'),
'validated_email' => 1,
'validated_at' => Carbon::now()->subDays(rand(0, 30)),
'last_login_at' => Carbon::now()->subDays(rand(0, 30)),
]);
// Preset Users and Schools
SchoolRoleUser::create([
'school_user_id' => $school_user->id,
'school_id' => $school->id,
'role_id' => $role->id,
]);
}
Related
I am creating an application where I have to insert a user at registration with custom fields. As found online, i customised the create method in the Laravel RegisterController. However, now the application inserts two user records whenever I register a new user. Can someone help me with this please?
Here is the code of my create method in the RegisterController
protected function create(array $data)
{
/********************************************************************************
* CALCULATE ALL THE NEEDED DATA FOR THE USER
********************************************************************************/
// Delete the uncompleted registration
UncompletedRegistration::deleteByEmail($data['email']);
// Set the right values based on the filled values
$compercentagecreative = 0.0;
$compercentagenotcreative = 0.0;
$creativepercent = 0.0;
switch ($data['headjob']) {
case 1:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.headjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.headjob');
$creativepercent = config('constants.percentageRates.creativePercent.headjob');
break;
case 2:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.notheadjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.notheadjob');
$creativepercent = config('constants.percentageRates.creativePercent.notheadjob');
break;
default:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.headjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.headjob');
$creativepercent = config('constants.percentageRates.creativePercent.headjob');
break;
}
// Format the VAT number
$data['vatnumber'] = Helper::formatVatNumber($data['vatnumber']);
$isVatValid = false;
try {
// Check if vat is valid
$response = Helper::checkVat($data['vatnumber']);
$responseArray = json_decode($response);
$isVatValid = $responseArray->valid;
} catch (\Exception $exception) {
$isVatValid = false;
}
// Generate an activation key
$activationKey = md5(uniqid('CS', true));
/********************************************************************************
* CREATE THE USER IN THE DATABASE
********************************************************************************/
// Create the user and insert in the database
return User::create([
'usertype' => config('constants.userTypes.USER'),
'registeredon' => strtotime(date("Y-m-d H:i:s")),
'activationkey' => $activationKey,
'language' => 'nl',
'email' => Helper::truncate($data['email']),
'fullname' => Helper::truncate($data['lastname'] . ' ' . $data['firstname']),
'firstname' => Helper::truncate($data['firstname']),
'lastname' => Helper::truncate($data['lastname']),
'password' => Hash::make($data['password']),
'lastloginon' => strtotime('now'),
'lastloginip' => $_SERVER['REMOTE_ADDR'],
'activatedon' => strtotime(date('Y-m-d H:i:s', strtotime('1970-01-01 00:00:00'))),
'deleted' => false,
'companyname' => Helper::truncate($data['companyname']),
'street' => Helper::truncate($data['street']),
'number' => Helper::truncate($data['number']),
'city' => Helper::truncate($data['city']),
'zipcode' => Helper::truncate($data['zipcode']),
'vatnumber' => Helper::truncate($data['vatnumber']),
'validvat' => $isVatValid,
'website' => Helper::truncate($data['website']),
'phonenumber' => Helper::truncate($data['phonenumber']),
'bankname' => Helper::truncate($data['bank']),
'iban' => Helper::truncate($data['iban']),
'bicswift' => Helper::truncate($data['bicswift']),
'paymentremindermode' => $data['paymentremindermode'],
'invoicecreationremindermode' => 2,
'nettosavedmailmode' => 1,
'zombiemailsent' => 0,
'zombiemail180sent' => 0,
'nettosavedperinvoicmailemode' => 1,
'logo' => NULL,
'emailaccepted' => false,
'contractaccepted' => false,
'compercentagecreative' => $compercentagecreative,
'compercentagenotcreative' => $compercentagenotcreative,
'contractdate' => date("Y-m-d H:i:s"),
'creativepercent' => $creativepercent,
'activity' => $data['activity'],
'headjob' => $data['headjob'],
'template' => config('constants.templates.ORIGINAL'),
'freebtw' => isset($data['freebtw']) ? ($data['freebtw'] == "on" ? true : false) : false,
'refid' => Input::get('invite_id'),
'api_key' => Helper::generateRandomString(40),
'allowed_quotation' => true,
'send_bcc' => false
]);
}
I've created a transaction but I'd like to return all data which has been created in one json. I'd like to do this using Resources in Laravel 5.5.
This is my transaction:
$firstUser = DB::transaction(function () use ($request) {
//Create Group Campany
$groupCompany = \App\GroupCompany::create([
'name' => $request['nameGroupCompany'],
'cod' => $request['codGroupCompany'],
]);
//Create Company
$company = \App\Company::create([
'group_company_id' => $groupCompany->id,
'name' => $request['nameCompany'],
'cod' => $request['codCompany'],
]);
//Create Group User
$groupUser = \App\GroupUser::create([
'name' => 'Admin',
'admin' => 1,
]);
$groupUser->companies()->attach($company->id);
//Create Person
$person = \App\Person::create([
'firstName' => $request['name'],
'middleName' => $request['middleName'],
'lastName' => $request['lastName'],
'dateOfBirth' => $request['dateOfBirth'],
]);
$person->groupUsers()->attach($groupUser->id);
//Create User
$newUser = \App\User::create([
'person_id' => $person->id,
'name' => $request['name'],
'email' => $request['email'],
'password' => bcrypt($request['password']),
]);
return ??????;
});
And finally I call my Resource:
return new FirstUserResource($firstUser);
What should I do?
Thank you very much.
Marcel
Save info in a array before save them like below:
$groupCompanya = array('name' => $request['nameGroupCompany'],
'cod' => $request['codGroupCompany']);
$groupCompany = \App\GroupCompany::create($groupCompanya);
Gather all data into a new array:
$result = array("groupCompany"=> $groupCompanya, "company" => $companya, "groupUser" => $groupUsera, "person"=>$persona, "newUser"=>$newUsera);
after convert it to json and return it:
$json = array("result" => $result);
return json_encode($json,JSON_UNESCAPED_UNICODE);
If you are returning all the data as a single json I think Collections will help you here?
$collection = collect([var1,var2]);
return $collection->toJson();
I'm trying to add a user to a list through an API. However, I'm getting this error returned:
{"errors":[{"code":"parsing_error","message":"JSON parsing error: The property '#/' of type Hash did not match one or more of the required schemas"}]}
This is what I'm sending: {"subscribers":{"email":"me#gmail.com"}}
Here is the PHP code:
$subscriberInfo = [
'subscribers' => array (
'email' => $email
)
];
$encoded = json_encode($subscriberInfo);
Is there something wrong with the structure of the JSON?
That's not the format described in the documentation. subscribers should be an array, not an object:
$subscriberInfo = [
'subscribers' => [
['email' => $email]
]
];
$encoded = json_encode($subscriberInfo);
Another possible issue that I encountered when receiving the same error code is that it didn't like a null value.
$firstName = 'Paul';
$lastName = null;
$subscriberInfo = [
'subscribers' => [
[
'email' => $email,
'first_name' => $firstName,
'last_name' => $lastName,
],
]
];
With the null coalescing operator, it can fall back to an empty string.
$firstName = 'Paul';
$lastName = null;
$subscriberInfo = [
'subscribers' => [
[
'email' => $email,
'first_name' => $firstName,
'last_name' => $lastName ?? '',
],
]
];
The above snippet resolved my error code when attempting a batch subscriber 'create or update'.
I am using sync (local driver) for pushing up a queue in a update method of EmailCampaignController, which uses another method of the same controller named emailQueue
like this
Queue::push('EmailNewsletterController#emailQueue', array('campaign_id' => $campaign_id));
The emailQueue uses a foreach loop which runs correctly for once after that it gives error as if the $campaign_id is undefined
here is the emailQueue method
public function emailQueue($job, $data) {
// Queue Starts here
$emailCampaign = EmailCampaign::find($data['campaign_id']);
$emailCampaign->status = 'In Progress';
$emailCampaign->last_activity = Carbon::now();
$emailCampaign->save();
$data = $emailCampaign->emailCampaignNewsletter;
$contacts = $emailCampaign->contactList->contacts;
foreach ($contacts as $contact) {
$emailBody = [
'message' => [
'subject' => $data['email_title'],
'html' => $data['email_body'],
'from_email' => $data['from_email'],
'to' => [['email' => $contact['email_address']]]
]
];
$response = Mandrill::request('messages/send', $emailBody);
EmailCampaignRecord::create([
'email_campaign_id' => $data['campaign_id'],
'mandrill_email_id' => $response[0]->_id,
'status' => $response[0]->status,
'to_email' => $contact['email_address']
]);
$contact->last_activity = Carbon::now();
$contact->save();
}
$emailCampaign->status = 'Sent';
$emailCampaign->save();
$job->delete();
// Ends here
}
What am I doing wrong here? why is it not working like a normal loop ?
The problem was with email_campaign_id to be null because $data['campaign_id'] was null the correct foreign key was $data['email_campaign_id'] that's what stopped the process - I should have tested it before putting it in the queue
after changing the code
EmailCampaignRecord::create([
'email_campaign_id' => $data['campaign_id'],
'mandrill_email_id' => $response[0]->_id,
'status' => $response[0]->status,
'to_email' => $contact['email_address']
]);
to
EmailCampaignRecord::create([
'email_campaign_id' => $data['email_campaign_id'],
'mandrill_email_id' => $response[0]->_id,
'status' => $response[0]->status,
'to_email' => $contact['email_address']
]);
the problem was solved
it may seem to be a silly question, but i dont know why, this thing isn't working for me.
I have an exisiting array
$data = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'password' => $enc_password,
'date_of_adding' => date('d/m/Y'),
'support_timestamp' => $timestamp
);
now i want to insert or append a new key with value into this existing array.
where the new key and its value is
'username' => $username
what i did is that
$data['username'] = $username;
but still the thing isn't working.
Can anybody tell what i am doing wrong??
try this
$data = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'password' => $enc_password,
'date_of_adding' => date('d/m/Y'),
'support_timestamp' => $timestamp
);
$data2 = array('username'=>$username);
$data = array_unshift($data,$data2);
You can do like this:
$data[]=array('username' => $username)
It will append the new array into an existing array
It should work using $data['username'] = $username;
Have a look at it here. Click the run icon
You may use
$data2 = array('username'=>$username);
$data = array_push($data,$data2);
or visit
demo