How to pass array values into the mail class one by one - laravel

I want to pass the values of array into the Mail class. I have this code where i get the emails.
Getting Emails from Database
$vendorsId = OrdersProduct::select('vendor_id')->where('order_id', $order_id)->pluck('vendor_id');
$vendorEmails = Admin::select('email')->whereIn('id', $vendorsId)->get()->toArray();
Result
array:2 [▼
0 => array:1 [▼
"email" => "mxxxxx#gmail.com"
]
1 => array:1 [▼
"email" => "myyyyy#gmail.com"
]
]
So i want to pass these email address into the mail class to send mail one by one, here below is the mail code
Sending Emails
$messageData = [
'order_id' => $order_id,
];
Mail::send('emails.order', $messageData, function ($message) use ($email) {
$message->to($email)->subject('Order Placed');
});
Thanks!

Why not use foreach?
$email = Auth::user()->email;
$messageData = [
'email' => $email,
'name' => Auth::user()->name,
'order_id' => $order_id,
'orderDetails' => $orderDetails,
];
foreach ($vendorEmails as $vemail) {
Mail::send('emails.order', $messageData, function ($message) use ($email, $vemail)
{
$message->to($vemail)->subject('Order Placed - stylooworld.info');
});
}

You can try like this ;
$emailList = Admin::->whereIn('id', $vendorsId)->pluck('email')->toArray();
Mail::send('emails.order', $messageData, function ($message) use ($emailList) {
$message->to($emailList)->subject('Order Placed');
});

Related

Laravel - How to pass variable as parameter to external API using guzzle

I am using Laravel-5.8 and Guzzle to consume an external api:
public function index()
{
try{
$myparam = 'JKK123';
$client = new Client();
$res = $client->request('GET','https://examplet/tracking/$myparam', [
'query' => ['key' => 'jkkffd091']
])->getBody();
$geoLocation = json_decode($res->getContents(), true);
$currentLocation = collect($geoLocation)->sortByDesc(function ($data) {
return Carbon::parse($data['Timestamp'])->format('d-m-Y h:i:s');
})->first();
$currentLocationFilter = explode(',', $currentLocation['current_asset_position_coord'] ?? '');
dd($currentLocationFilter);
return view('index', [
'currentLocation' => $currentLocation,
'currentLocationFilter' => $currentLocationFilter,
'geoLocation' => $geoLocation
]);
}catch (Exception $exception) {
Log::error($exception);
return back();
}
}
I am trying to pass the variable as parameter to the API. I didn't put it directly because it changes. I just tried to test.
When I did this as shown in the code above
$res = $client->request('GET','https://examplet/tracking/$myparam', [ ...
and then
dd($currentLocationFilter);
I got:
array:1 [▼
0 => ""
]
But when I put the value directly,
$res = $client->request('GET','https://examplet/tracking/JKK123', [
I got the required result:
array:2 [▼
0 => "2.1234565432145"
1 => "1.7864321249555"
]
How do I paa the variable as parameter into the external API?
Thanks
Use double quotes for executing variable like this:
$res = $client->request('GET',"https://examplet/tracking/{$myparam}", [...

get a data from an array

get a data from an array ..code for getting cart
public function show()
{
$data = $this->cartService->getCart(auth()->user()->id);
dd($data);
}
Response
array:2 [
"cart" => array:9 [
"id" => 244
"user_id" => 53
"total_mrp" => "56000.00"
"promo" => "HELLO"
"discount" => "30.00"
"meta" => {#1575
+"sub_total": 56000
}
]
"cart_items" => array:1 [
]
]
]
]
HOW CAN I GET PROMO IN A Variabel???
i tried
return $data->promo;
but error
You can use collect(). You can read about this function from laravel doc
$data = $this->cartService->getCart(auth()->user()->id);
$cart = collect($data['cart']??[]);
dd($cart->get('promo'));

Srmklive\PayPal error "Object of class Illuminate\Routing\Redirector could not be converted to string" trying express checkout in sandbox

Hello I'm trying to integrate Paypal in a Laravel 5.8 project using Srmklive\PayPal.
I followed the documentation and configured my application like this:
this is the controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Srmklive\PayPal\Services\ExpressCheckout;
class PayPalController extends Controller
{
/**
* Responds with a welcome message with instructions
*
* #return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function payment()
{
$data = [];
$data['items'] = [
[
'name' => 'ItSolutionStuff.com',
'price' => 100,
'desc' => 'Description for ItSolutionStuff.com',
'qty' => 1
]
];
$data['invoice_id'] = 1;
$data['invoice_description'] = "Order #{$data['invoice_id']} Invoice";
$data['return_url'] = route('payment.success');
$data['cancel_url'] = route('payment.cancel');
$data['total'] = 100;
$provider = new ExpressCheckout;
$response = $provider->setCurrency('EUR')->setExpressCheckout($data);
//dd($response);
return redirect($response['paypal_link']);
}
/**
* Responds with a welcome message with instructions
*
* #return \Illuminate\Http\Response
*/
public function cancel()
{
dd('Your payment is canceled. You can create cancel page here.');
}
/**
* Responds with a welcome message with instructions
*
* #return \Illuminate\Http\Response
*/
public function success(Request $request)
{
$response = $provider->getExpressCheckoutDetails($request->token);
if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
dd('Your payment was successfully. You can create success page here.');
}
dd('Something is wrong.');
}
}
These are the routes:
Route::get('payment', 'PayPalController#payment')->name('payment');
Route::get('cancel', 'PayPalController#cancel')->name('payment.cancel');
Route::get('payment/success', 'PayPalController#success')->name('payment.success');
and finally this is what I put in the .env file:
PAYPAL_SANDBOX_API_USERNAME=sb-xxxxxxxx.com
PAYPAL_SANDBOX_API_PASSWORD=KxxxxxxxxxWA
PAYPAL_SANDBOX_API_SECRET=Exxxxxxxxxxxxx
PAYPAL_SANDBOX_API_CERTIFICATE=
The error I got if I click on the payment button is "Object of class Illuminate\Routing\Redirector could not be converted to string"
this is the content of the dump of $response generated in the controller
thank you for your help
This is the dump of my $provider variable.... I really don't know where to find the error... it seems everything properly setted
Srmklive\PayPal\Services\ExpressCheckout {#299 ▼
-client: GuzzleHttp\Client {#300 ▼
-config: array:9 [▶]
}
-httpClientConfig: array:2 [▶]
-certificate: ""
+mode: "sandbox"
#post: Illuminate\Support\Collection {#321 ▼
#items: array:21 [▼
"L_PAYMENTREQUEST_0_NAME0" => "ItSolutionStuff.com"
"L_PAYMENTREQUEST_0_AMT0" => 100
"L_PAYMENTREQUEST_0_DESC0" => "Description for ItSolutionStuff.com"
"L_PAYMENTREQUEST_0_QTY0" => 1
"PAYMENTREQUEST_0_ITEMAMT" => 100
"PAYMENTREQUEST_0_AMT" => 100
"PAYMENTREQUEST_0_PAYMENTACTION" => "Sale"
"PAYMENTREQUEST_0_CURRENCYCODE" => "EUR"
"PAYMENTREQUEST_0_DESC" => "Order #1 Invoice"
"PAYMENTREQUEST_0_INVNUM" => 1
"NOSHIPPING" => 1
"RETURNURL" => "http://127.0.0.1:8000/payment/success"
"CANCELURL" => "http://127.0.0.1:8000/cancel"
"LOCALE" => "en_US"
"L_BILLINGTYPE0" => "MerchantInitiatedBilling"
"L_BILLINGAGREEMENTDESCRIPTION0" => "Order #1 Invoice"
"USER" => "sb-4lmkp2417467_api1.business.example.com"
"PWD" => "KWP3ZMXTAABSECWA"
"SIGNATURE" => "ENX8hFsccoYGDiPXfROILYkMlkRTCkdCRdBQZ-prMaOGLpE7sm7TRaZSFFd4KQI14LAShVhvDZN9sSDh"
"VERSION" => 123
"METHOD" => "SetExpressCheckout"
]
}
-config: array:12 [▼
"username" => "sb-4lmkp2417467_api1.business.example.com"
"password" => "KWP3ZMXTAABSECWA"
"secret" => "ENX8hFsccoYGDiPXfROILYkMlkRTCkdCRdBQZ-prMaOGLpE7sm7TRaZSFFd4KQI14LAShVhvDZN9sSDh"
"certificate" => ""
"app_id" => "APP-80W284485P519543T"
"signature" => "ENX8hFsccoYGDiPXfROILYkMlkRTCkdCRdBQZ-prMaOGLpE7sm7TRaZSFFd4KQI14LAShVhvDZN9sSDh"
"api_url" => "https://api-3t.sandbox.paypal.com/nvp"
"gateway_url" => "https://www.sandbox.paypal.com"
"ipn_url" => "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr"
"payment_action" => "Sale"
"notify_url" => ""
"locale" => ""
]
-subtotal: 100
-currency: "EUR"
-billingType: "MerchantInitiatedBilling"
-options: []
-paymentAction: "Sale"
-locale: "en_US"
-apiUrl: "https://api-3t.sandbox.paypal.com/nvp"
-notifyUrl: ""
-httpBodyParam: "form_params"
-validateSSL: true
}

Laravel parameterBag as array issues when inserting

I am trying to insert mass data but i get this error when i iterate through the request:
Symfony\Component\Debug\Exception\FatalThrowableError Cannot use
object of type Symfony\Component\HttpFoundation\ParameterBag as array
Request example:
request: Symfony\Component\HttpFoundation\ParameterBag {#52 ▼
#parameters: array:4 [▼
"_token" => "Z1sF2K5LHU1bsQ4l3JRaOLCTQDmJ47qakigmrfI5"
"name" => "Rousaddasd 1"
"secsaddsans" => array:1 [▼
"secsdfs1" => array:2 [▼
"name" => "Sectdfs 1"
]
]
"submit" => "Submit"
]
}
Loop to go through the request and insert:
$abc = new abc;
$abc->create(['user_id' => 1, 'name' => $request->name, 'description' => 'test description']);
foreach($request as $item){
$asd = new asd;
$asd->name = $item['name'];
$asd->description = 'test description';
$abc->asds()->create([$asd]);
}
Im adding some data "inline" because i didnt handle them in the form yet, thats why the added duration and duration_unit for example.
You can use $request as array like this:
$request = $request->all();
And loop like:
foreach($request['sections'] as $item) {
....
foreach($item['exercises'] as $item2) {
....
}
}

Map array values to collection of items

How would one do the following elegantly with laravel collections ?
Map the values of the $baseMap as keys to the collection.
The baseMap :
$baseMap = [
'name' => 'new_name',
'year' => 'new_year',
];
The collection :
$items = collect([
[
'name' => 'name1',
'year' => '1000',
'not_in_basemap' => 'foo'
],
[
'name' => 'name2',
'year' => '2000',
'not_in_basemap' => 'foo'
],
//...
]);
The end result :
$result =[
[
'new_name' => 'name1',
'new_year' => '1000',
],
[
'new_name'=> 'name2',
'new_year' => '2000',
],
];
I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!
I tried to find collection methods, or php functions, but without success. Some dirty code that works with different keys from both sides (items and basemap).
$result = $items->map(function($item) use ($baseMap) {
$array = [];
foreach($baseMap as $oldKey => $newKey){
if(isset($item[$oldKey])){
$array[$newKey] = $item[$oldKey];
}
}
return $array;
});
$result = $result->toArray();
Thanks to #vivek_23 and #IndianCoding for giving me idea's I ended up with the following :
I made a small edit to make sure the mapping and the items keys lined up.
so you don't have to worry of misalignment and all in laravel collection !
$baseMap = collect($baseMap)->sortKeys();
$result = $items->map(function ($item) use ($baseMap) {
return $baseMap->values()
->combine(
collect($item)->sortKeys()->intersectByKeys($baseMap)
)
->all();
});
Use intersectByKeys to filter your baseMap keys with $items values.
$result = $items->map(function($item,$key) use ($baseMap){
return array_combine(array_values($baseMap),collect($item)->intersectByKeys($baseMap)->all());
});
dd($result);
Update:
In a pure collection way,
$baseMapCollect = collect($baseMap);
$result = $items->map(function($item,$key) use ($baseMapCollect){
return $baseMapCollect->values()->combine(collect($item)->intersectByKeys($baseMapCollect->all())->values())->all();
});
dd($result);
Here are my two cents, using map. Don't know how dynamic your collection should be, but knowing the keys I would do the following:
$baseMap = [
'name' => 'new_name',
'year' => 'new_year',
];
$items = collect([
[
'name' => 'name1',
'year' => '1000',
'not_in_basemap' => 'foo'
],
[
'name' => 'name2',
'year' => '2000',
'not_in_basemap' => 'foo'
],
])->map(function($item, $key) use ($baseMap) {
return [
$baseMap['name'] => $item['name'],
$baseMap['year'] => $item['year']
];
});

Resources