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();
Related
Please am trying to upload 3 different images using the code below. How do I get each of the methods that generates the unique image names to run only when their respective request fields have data or is not empty. thus the form submit should not try generating any image name for afile field when that particular file field is empty.
My update controller function
public function update(Request $request, Product $product)
{
$image = $request->file('primary_image');
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
$image_1 = $request->file('image_1');
$name_gen = md5(rand(1000, 10000)).'.'.$image_1->getClientOriginalExtension();
Image::make($image_1)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url_1 = 'upload/products/'.$name_gen;
$image_2 = $request->file('image_2');
$name_gen = md5(rand(1000, 10000)).'.'.$image_2->getClientOriginalExtension();
Image::make($image_2)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url_2 = 'upload/products/'.$name_gen;
Product::insert([
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $save_url,
'image_1' => $save_url_1,
'image_2' => $save_url_2,
]);
$notification = array(
'message' => 'Product updated successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Thanks so much for taking time to review my code
Since you are doing the same name generation process all through, you can use an array and do a foreach loop with an if condition like this:
$my_array = [$request->file('primary_image'), $request->file('image_1'), $request->file('image_2')];
foreach($my_array as $item) {
if($item) {
$image = $item;
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
}
}
Now this will only generate names for images that are not empty.
UPDATE:
For the insert functionality, I would assume your table fields for the images can have null values, so this doesn't throw an error. Now instead of the code above, do this:
$my_array = [$request->file('primary_image'), $request->file('image_1'), $request->file('image_2')];
$insert_array = [];
foreach($my_array as $item) {
$save_url = '';
if($item) {
$image = $item;
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
}
array_push($insert_array, $save_url);
}
Now for your insert query, do this:
Product::insert([
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $insert_array[0],
'image_1' => $insert_array[1],
'image_2' => $insert_array[2],
]);
This would work.
I try to have logic in my transaction, but it just keeps adding the data to the database and I don't know what's going wrong...
The code I currently have:
public function addQuote($customer_id, Request $request)
{
//try catch, since there can be errors in it
DB::transaction(function() use ($customer_id, $request) {
try {
// Make a project for a quote, but not a main project, to not interfere with other existing projects
$quote_project = QuoteProject::create([
'projectnumber' => $request->project_number,
'name' => $request->project_name,
'address' => $request->project_address,
'zipcode' => $request->project_zipcode,
'city' => $request->project_city,
'country' => $request->project_country ?? 'BE',
'customer_id' => $customer_id,
]);
// Make a quote
$quote = Quote::create([
'status_id' => 1, // assign pending status
'reference' => $request->reference,
'number' => rand(),
'department_id' => $request->department,
'project_id' => $quote_project->id, // Created project id
'location_id' => ($request->location === 0) ? null : $request->location, // location -> can be 0 as value, if so, leave empty
'customer_id' => $customer_id,
'contact_id' => $request->contact_id,
'layout_id' => $request->layout_id,
'seller_id' => $request->seller_id,
'date_from' => Carbon::createFromFormat('d/m/Y', $request->date_from)->format('Y-m-d'),
'date_till' => Carbon::createFromFormat('d/m/Y', $request->date_till)->format('Y-m-d'),
'document_number' => $request->document_number,
'customer_number' => $request->customer_number,
'vat_type_id' => $request->vat_type_id,
'vat_tariff_id' => $request->vat_tariff_id,
]);
$quote->conditions()->attach($request->payment_conditions);
if (isset($request->head_group)) {
// set a global sync data variable
$sync_data = [];
// Loop over all the head groups
foreach ($request->head_group as $key => $head_group) {
// create or update head group
$created_head_group = ArticleGroup::updateOrCreate([
'quote_id' => $quote->id,
'name' => $head_group ?? ''
], [
'comment' => $request->head_group_comment[$key] ?? '',
'head_group' => 1,
'parent_group' => null,
'bold' => filter_var($request->bold_head[$key], FILTER_VALIDATE_BOOLEAN) ?? false,
'italic' => filter_var($request->italic_head[$key], FILTER_VALIDATE_BOOLEAN) ?? false,
'underline' => filter_var($request->underline_head[$key], FILTER_VALIDATE_BOOLEAN) ?? false,
'color' => str_replace('#', '', $request->color_head[$key]) ?? null
]);
// Loop over the sub groups in a main group
foreach ($request->sub_group[$key] as $s_key => $sub_group) {
// Create or update a subgroup
$created_sub_group = ArticleGroup::updateOrCreate([
'quote_id' => $quote->id,
'name' => $sub_group ?? ''
], [
'comment' => $request->sub_group_comment[$key][$s_key] ?? '',
'head_group' => 0,
'parent_group' => $created_head_group->id,
'bold' => filter_var($request->bold_sub[$key][$s_key], FILTER_VALIDATE_BOOLEAN) ?? false,
'italic' => filter_var($request->italic_sub[$key][$s_key], FILTER_VALIDATE_BOOLEAN) ?? false,
'underline' => filter_var($request->underline_sub[$key][$s_key], FILTER_VALIDATE_BOOLEAN) ?? false,
'color' => str_replace('#', '', $request->color_sub[$key][$s_key]) ?? null
]);
// Loop over the articles in the subgroup
foreach ($request->articles[$key][$s_key] as $a_key => $article_id) {
if (isset($request->articles[$key][$s_key])) {
$id = explode('-', $article_id);
$sync_data[$id[0]] = [
'name' => $request->custom_article_name[$key][$s_key][$a_key],
'quantity' => $request->quantity[$key][$s_key][$a_key],
'thickness' => $request->thickness[$key][$s_key][$a_key],
'price' => $request->article_price[$key][$s_key][$a_key],
'description' => $request->description[$key][$s_key][$a_key],
'group_id' => $created_sub_group->id
];
}
}
}
}
$quote->articles()->sync($sync_data); // sync the articles
}
// return data for ajax call, since the wizard works via an ajax call submit
return url('customers/' . $customer_id . '/quotations/');
} catch (\Exception $ex) {
return response()->json(['error' => $ex->getMessage()], 500);
}
}
);
}
If someone could explain me what I'm doing wrong here, that would be a really great help!
This is how it works. If inside DB::transaction exception is thrown then transaction is rolled back automatically. However in your implementation exception is not thrown because you catch it inside transaction and just try to return error response (what by the way won't work because you miss return in DB::transaction(function() use ($customer_id, $request) { line).
The easiest way to solve is to catch exception not inside DB::transaction but outside of it - then it will behave as you expected, transaction will be rolled back.
Alternative solution in some cases it not using DB::transaction but instead using manual:
DB::beginTransaction();
DB::rollBack();
DB::commit();
as described in documentation.
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 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
I'm trying create programmatically a new address to customers that was imported a some time ago for me.
My Code:
//All variables about customer address info are filled
$customerModel = Mage::getModel('customer/customer');
$customer = $customerModel->setWebsiteId(1)->loadByEmail($_email);
if($customer->getId()) {
$addressData = array (
'firstname' => $customer->getFirstname(),
'lastname' => $customer->getLastname(),
'street' => "$_s1
$_s2
$_s3
$_s4",
'city' => $_city,
'country_id' => 'BR',
'region_id' => $_regionid,
'postcode' => $_cep,
'telephone' => $_tel,
'celular' => $_cel,
'is_default_billing' => 1,
'is_default_shipping' => 1
);
$address = Mage::getModel('customer/address');
$address->addData($addressData);
$customer->addAddress($address);
try {
print_r($addressData);
$customer->save();
}
catch (Exception $e) {
}
}
Object loaded '$customer' isnt what I need: a full customer object.
Any Idea?
You have to save customer address in different way, following is address saving code.
$customerAddress = Mage::getModel('customer/address');
$customerAddress->setData($addressData)
->setCustomerId($customer->getId())
->setSaveInAddressBook('1');
$customerAddress->save();
The full code will look like:
$customerModel = Mage::getModel('customer/customer');
$customer = $customerModel->setWebsiteId(1)->loadByEmail($_email);
if($customer->getId()) {
$addressData = array (
'firstname' => $customer->getFirstname(),
'lastname' => $customer->getLastname(),
'street' => "$_s1
$_s2
$_s3
$_s4",
'city' => $_city,
'country_id' => 'BR',
'region_id' => $_regionid,
'postcode' => $_cep,
'telephone' => $_tel,
'celular' => $_cel,
'is_default_billing' => 1,
'is_default_shipping' => 1
);
$customerAddress = Mage::getModel('customer/address');
$customerAddress->setData($addressData)
->setCustomerId($customer->getId())
->setSaveInAddressBook('1');
$customerAddress->save();
//And reload customer object
$customer = Mage::getModel('customer/customer')->load($customer->getId());
//Check customer data
print_r($customer->getData());
//Check addresses
foreach($customer->getAddresses() as $address)
{
print_r($address);
}
}