Can anyone please point me on how to update a firestore document with its id. I am able to create a document and update it using the laravel-firebase package by kreait.
My below code creates the document on firestore. However, how do I update this same document with the document reference or id.
$groupsRef = app('firebase.firestore')->database()->collection('groups');
$groupData = [
'groupAdmin' => auth()->user()->id."_".auth()->user()->name,
'groupDescription' => $request->group_description,
'groupIcon' => $image,
'groupId' => '',
'groupMembers' => [
auth()->user()->id."_".auth()->user()->name
],
'groupName' => $request->group_name,
'recentMessage' => '',
'recentMessageSender' => '',
'recentMessageTime' => ''
];
$groupsRef->add($groupData);
The below implementation updates the document with its name and not its reference.
$document = $groupsRef->document($request->group_name);
$groupId = $document->id();
$updatedGroupData = [
'groupAdmin' => auth()->user()->id."_".auth()->user()->name,
'groupDescription' => $request->group_description,
'groupIcon' => $request->hasFile('groupIcon') ? $image : '',
'groupId' => $groupId,
'groupMembers' => [
auth()->user()->id."_".auth()->user()->name
],
'groupName' => $request->group_name,
'recentMessage' => '',
'recentMessageSender' => '',
'recentMessageTime' => ''
];
$updatedFitfam = $document->update($updatedGroupData);
The Firestore add return the document reference from where you can get the document id. Then update as following :
$groupsRef = app('firebase.firestore')->database()->collection('groups');
$groupData = [
'groupAdmin' => auth()->user()->id."_".auth()->user()->name,
'groupDescription' => $request->group_description,
'groupIcon' => $image,
'groupId' => '',
'groupMembers' => [
auth()->user()->id."_".auth()->user()->name
],
'groupName' => $request->group_name,
'recentMessage' => '',
'recentMessageSender' => '',
'recentMessageTime' => ''
];
$docId = $groupsRef->add($groupData);
$updatedGroupData = [
'groupAdmin' => auth()->user()->id."_".auth()->user()->name,
'groupDescription' => $request->group_description,
'groupIcon' => $request->hasFile('groupIcon') ? $image : '',
'groupId' => $groupId,
'groupMembers' => [
auth()->user()->id."_".auth()->user()->name
],
'groupName' => $request->group_name,
'recentMessage' => '',
'recentMessageSender' => '',
'recentMessageTime' => ''
];
$updatedFitfam = $document->update($docId->id());
If you want to get the document from the $groupsRef using $request->group_name then use this workaround that should work:
$groupsRef = app('firebase.firestore')->database()->collection('groups');
$document = $groupsRef->document($request->group_name);
$snapshot = $document->get();
if ($snapshot->exists()) {
$existingData = $snapshot->data();
$updatedGroupData = [
'groupAdmin' => auth()->user()->id."_".auth()->user()->name,
'groupDescription' => $request->group_description,
'groupIcon' => $request->hasFile('groupIcon') ? $image : '',
'groupMembers' => array_merge(
$existingData['groupMembers'] ?? [],
[auth()->user()->id."_".auth()->user()->name]
),
'recentMessage' => $existingData['recentMessage'] ?? ' ',
'recentMessageSender' => $existingData['recentMessageSender'] ?? ' ',
'recentMessageTime' => $existingData['recentMessageTime'] ?? ' '
];
$document->update($updatedGroupData);
}
Reference taken from this docs
Related
I am using the stripe/stripe package to capture payment for single product. Everything is working as expected however when the user is returned to the order-confirmation page, I would like to get the stripe payment id. How would i achieve this?
Im not sure if i need a webhook and if i would, how would i use this?
public function onCharge() {
$user = Auth::getUser();
$course = CourseMeta::where('id', $this->param('id'))->first();
$stripe = new \Stripe\StripeClient(env('STRIPE_SECRET'));
$product = $stripe->products->create([
'name' => $course->course->name . ' - ' . $course->date,
]);
$price = $stripe->prices->create([
'unit_amount' => $course->price * 120,
'currency' => 'gbp',
'product' => $product->id,
]);
$validator = Validator::make(
[
'user_id' => $user->id,
'coursemeta_id' => $course->id,
'course_id' => $course->course->id,
'stripe_id' => '1',
],
[
'user_id' => 'required',
'coursemeta_id' => 'required',
'course_id' => 'required',
'stripe_id' => 'required'
]
);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator);
} else {
$order = new Order();
$order->user_id = $user->id;
$order->coursemeta_id = $course->id;
$order->stripe_id = '1';
$order->company = request()->get('company');
$order->company_firstname = request()->get('company_firstname');
$order->company_lastname = request()->get('company_lastname');
$order->company_email = request()->get('company_email');
$order->company_phone = request()->get('company_phone');
$order->citb_levy = request()->get('citb_levy');
$order->d_firstname = request()->get('d_firstname');
$order->d_lastname = request()->get('d_lastname');
$order->d_email = request()->get('d_email');
$order->d_phone = request()->get('d_phone');
$order->d_dob = request()->get('d_dob');
$order->d_ninumber = request()->get('d_ninumber');
$order->save();
}
$portal = $stripe->checkout->sessions->create([
'success_url' => env('APP_URL') . '/order-confirmation'.'?' . 'user=' . $user->id . '&' . 'course=' . $course->id,
'cancel_url' => env('APP_URL') . '/cancel',
'line_items' => [
[
'price' => $price->id,
'quantity' => 1
],
],
'mode' => 'payment',
]);
return redirect($portal->url);
}
You need to use the checkout session ID.
when you create success_url and cancel_url you can also pass {CHECKOUT_SESSION_ID} param with curly braces. when payment gateway will redirect to one of those URLs it will automatically replace {CHECKOUT_SESSION_ID} with the actual session ID.
In your case
$portal = $stripe->checkout->sessions->create([
// HERE ---------------------------------------------------\/----------\/
'success_url' => env('APP_URL') . '/order-confirmation'.'?session_id={CHECKOUT_SESSION_ID}&' . 'user='. $user->id . '&' . 'course=' . $course->id,
'cancel_url' => env('APP_URL') . '/cancel',
'line_items' => [
[
'price' => $price->id,
'quantity' => 1
],
],
'mode' => 'payment',
]);
Now when this page is called you can have session ID and you can retrieve all stuff from it.
// on success or cancel page you can use this code to get infos
$stripe = new \Stripe\StripeClient(env('STRIPE_SECRET'));
$session = \Stripe\Checkout\Session::retrieve(get('session_id'));
$customer = \Stripe\Customer::retrieve($session->customer);
$paymentIntent = \Stripe\PaymentIntent::retrieve($session->payment_intent);
// from this $session you can get customer/items/paymentIntent etc..
ref : https://stripe.com/docs/payments/checkout/custom-success-page
if any doubt please comment.
how to update data in database with import excel if data exist just update, and if not exist just save. i am using laravel 5.8 and maatwebsite 2.1
this is my controller :
$request->validate([
'file' => 'required|mimes:csv,xls,xlsx',
'divisi' => 'required',
'file_type' => 'required'
]);
$path = $request->file('file')->getRealPath();
$data = Excel::load($path)->first();
$divisi = $request->input('divisi');
$file_type = $request->input('file_type');
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$arr[] = [
'product_id' => $value->product_id,
'upc' => $value->upc,
'desc_a' => $value->desc_a,
'name' => $value->name,
'category' => $value->category,
'desc_b' => $value->desc_b,
'desc_c' => $value->desc_c,
'desc_d' => $value->desc_d,
'desc_e' => $value->desc_e,
'desc_f' => $value->desc_f,
'desc_g' => $value->desc_g,
'desc_h' => $value->desc_h,
'fixel_id' => $value->fixel_id,
'x' => $value->x,
'cost' => $value->cost,
'price' => $value->price,
'reg_movement' => $value->reg_movement,
'total_facings' => $value->total_facings,
'total_units' => $value->total_units,
'days_of_supply' => $value->days_of_supply,
'desc_i' => $value->desc_i,
'kode_lokasi' => $value->kode_lokasi,
'created_by' => Auth::user()->id,
'updated_by' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
'divisi' => $divisi,
'file_type' => $file_type];
}
if(!empty($arr)){
Planogram::updateOrCreate($arr);
} }
from this code my data always multiply with same record.
thank you
Done, just change to this
if($data->count()){
foreach ($data as $key => $value) {
$getsku = PlanogramTemp::updateOrCreate([
'desc_b' => $value->desc_b,
'desc_e' => $value->desc_e
],[
'product_id' => $value->product_id,
'upc' => $value->upc,
'desc_a' => $value->desc_a,
'name' => $value->name,
'category' => $value->category,
'desc_b' => $value->desc_b,
'desc_c' => $value->desc_c,
'desc_d' => $value->desc_d,
'desc_e' => $value->desc_e,
'desc_f' => $value->desc_f,
'desc_g' => $value->desc_g,
'desc_h' => $value->desc_h,
'fixel_id' => $value->fixel_id,
'x' => $value->x,
'cost' => $value->cost,
'price' => $value->price,
'reg_movement' => $value->reg_movement,
'total_facings' => $value->total_facings,
'total_units' => $value->total_units,
'days_of_supply' => $value->days_of_supply,
'desc_i' => $value->desc_i,
'kode_lokasi' => $value->kode_lokasi,
'created_by' => Auth::user()->id,
'updated_by' => Auth::user()->id,
'divisi' => $divisi,
'file_type' => $file_type]);
}
First I get the translator by his id using this line of code
$translator = Translator::where('id', $translator_id)->first();
Then I send a notification to him by this code:
$response = Http::withHeaders([
'Authorization' => 'key=myKey',
'Content-Type' => 'application/json'
])->post('https://fcm.googleapis.com/fcm/send', [
"notification" => [
"title" => "title",
"body" => "body",
],
"data" => [
"title" => "title",
"body" => "body",
],
"to" => $token,
]);
Everything works fine but my problem is that when I return the TranslatorResource I want to add the notification response to it, so I do this in my controller
$resource = new TranslatorResource($translator);
$resource->notif = $response;
return $resource;
And in TranslatorResource I have this code:
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'phone' => $this->phone,
'cv' => $this->cv,
'specialization' => $this->specialization,
'tr_languages' => $this->tr_languages,
'all_languages' => $this->all_languages,
'isVerified' => $this->isVerified == 0 ? false : true,
'isActive' => $this->isActive == 0 ? false : true,
'completed_orders' => $this->completed_orders,
'canceled_orders' => $this->canceled_orders,
'rejected_orders' => $this->rejected_orders,
'current_orders' => $this->current_orders,
'isTranslator' => true,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
But I only get the data specified in the resource, the notif key isn't added, anyone know how to add this data to my resource when I return it ?
You can use additional method provided by laravel.
return (new TranslatorResource($translator))->additional(['notif ' => $response]);
Reference: Eloquent: API Resources
You can look for the section Adding Meta Data When Constructing Resources.
I have the following in my view:
Pay with PayPal
Defined the route:
Route::get('pay-with-paypal', 'CheckoutController#payWithPaypal')->name('payment.paypal');
My CheckoutController looks like the one below:
use Srmklive\PayPal\Services\ExpressCheckout;
class CheckoutController extends Controller
{
public function payWithPaypal(){
$provider = new ExpressCheckout;
$data = [];
$data['items'] = [
[
'name' => 'Product 1',
'price' => 9.99,
'qty' => 1
],
[
'name' => 'Product 2',
'price' => 4.99,
'qty' => 2
]
];
$data['invoice_id'] = 1;
$data['invoice_description'] = "Order #{$data['invoice_id']} Invoice";
$data['return_url'] = url('/');
$data['cancel_url'] = url('/');
$total = 0;
foreach($data['items'] as $item) {
$total += $item['price']*$item['qty'];
}
$data['total'] = $total;
$response = $provider->setExpressCheckout($data);
// This will redirect user to PayPal
return redirect($response['paypal_link']);
}
}
My config looks like this:
return [
'mode' => 'sandbox', // Can only be 'sandbox' Or 'live'. If empty or invalid, 'live' will be used.
'sandbox' => [
'username' => env('PAYPAL_SANDBOX_API_USERNAME', ''),
'password' => env('PAYPAL_SANDBOX_API_PASSWORD', ''),
'secret' => env('PAYPAL_SANDBOX_API_SECRET', ''),
'certificate' => env('PAYPAL_SANDBOX_API_CERTIFICATE', ''),
'app_id' => 'APP-80W284485P519543T', // Used for testing Adaptive Payments API in sandbox mode
],
'live' => [
'username' => env('PAYPAL_LIVE_API_USERNAME', ''),
'password' => env('PAYPAL_LIVE_API_PASSWORD', ''),
'secret' => env('PAYPAL_LIVE_API_SECRET', ''),
'certificate' => env('PAYPAL_LIVE_API_CERTIFICATE', ''),
'app_id' => '', // Used for Adaptive Payments API
],
'payment_action' => 'Sale', // Can only be 'Sale', 'Authorization' or 'Order'
'currency' => 'USD',
'billing_type' => 'MerchantInitiatedBilling',
'notify_url' => '', // Change this accordingly for your application.
'locale' => '', // force gateway language i.e. it_IT, es_ES, en_US ... (for express checkout only)
'validate_ssl' => true, // Validate SSL when creating api client.
];
My .env is also configured:
PAYPAL_SANDBOX_API_USERNAME=example-facilitator_api1.hotmail.com
PAYPAL_SANDBOX_API_PASSWORD=SLU2YLP4B
PAYPAL_SANDBOX_API_SECRET=TF3K8CtWTEmAcRu40.XWAihLRko
PAYPAL_SANDBOX_API_CERTIFICATE=
When I click on the link "Pay with PayPal", nothing happens. Anything I could have possibly done wrong?
Reference: https://github.com/srmklive/laravel-paypal
I'm trying to import an excel to my database table 'users' but it has an error saying Illegal string offset "email". I tried deleting the "email" then it says that Illegal string offset "username" now. Is it really the error in controller? Or maybe the reason is that i also have a repository.
This is my code for the controller
public function userImport()
{
if( Input::file('file_import') ) {
$path = Input::file('file_import')->getRealPath();
$inserts = [];
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $rows){
foreach($rows as $row){
$inserts[] = ['email' => $row['email'], 'username' => $row
['username'], 'password' => $row['password'], 'first_name' => $row['first_name'],'middle_name' => $row['middle_name'], 'last_name' => $row['last_name'], 'gender' => $row['gender'],
'civil_status' => $row['civil_status'], 'spouse' => $row['spouse'], 'religion' => $row['religion'],'emergency_no' => $row['emergency_no'],'previous_work' => $row['previous_work'],
'remarks' => $row['remarks'],'course' => $row['course'],'biometrics' => $row['biometrics'],'immediate_head' => $row['immediate_head'],'designation' => $row['designation'],'level' => $row['level'],
'emp_status' => $row['emp_status'],'dependents' => $row['dependents'],'date_hired' => $row['date_hired'],'regularization_date' => $row['regularization_date'],'remmitance_date' => $row['remmitance_date'],
'tin' => $row['tin'],'philhealth' => $row['philhealth'],'pagibig' => $row['pagibig'],'sss' => $row['sss'],'umid' => $row['umid'],'phone' => $row['phone'],'avatar' => $row['avatar'],
'address' => $row['address'],'country_id' => $row['country_id'],'role_id' => $row['role_id'],'birthday' => $row['birthday'],'status' => $row['status']];
}
}
});
}
if (!empty($inserts)) {
DB::table('users')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}
return back();
}
As per your dumped $rows, it looks like that you don't need another foreach inside another foreach, modify your code.
// readability purpose
$rows = $reader->toArray();
foreach ($rows as $row){
$inserts[] = ['email' => $row['email'], 'username' => $row
['username'], 'password' => $row['password'], 'first_name' => $row['first_name'],'middle_name' => $row['middle_name'], 'last_name' => $row['last_name'], 'gender' => $row['gender'],
'civil_status' => $row['civil_status'], 'spouse' => $row['spouse'], 'religion' => $row['religion'],'emergency_no' => $row['emergency_no'],'previous_work' => $row['previous_work'],
'remarks' => $row['remarks'],'course' => $row['course'],'biometrics' => $row['biometrics'],'immediate_head' => $row['immediate_head'],'designation' => $row['designation'],'level' => $row['level'],
'emp_status' => $row['emp_status'],'dependents' => $row['dependents'],'date_hired' => $row['date_hired'],'regularization_date' => $row['regularization_date'],'remmitance_date' => $row['remmitance_date'],
'tin' => $row['tin'],'philhealth' => $row['philhealth'],'pagibig' => $row['pagibig'],'sss' => $row['sss'],'umid' => $row['umid'],'phone' => $row['phone'],'avatar' => $row['avatar'],
'address' => $row['address'],'country_id' => $row['country_id'],'role_id' => $row['role_id'],'birthday' => $row['birthday'],'status' => $row['status']];
}
$rows already represents each row, so you should probably rename it to $row.