Laravel parameterBag as array issues when inserting - laravel

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) {
....
}
}

Related

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

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');
});

I want to sort the related values that are obtained by contain in pagination (CakePHP4)

Get the value of contain for the Slugs associated with the Posts model.
I want to sort them in order of the ID of the retrieved Slugs table.
in PostsController
/**
* Index method
*
* #return \Cake\Http\Response|null|void Renders view
*/
public function index()
{
$this->paginate = [
'limit' => 10,
'contain' => ['Slugs'],
'order' => [
'Slugs.id' => 'desc',
],
];
$posts = $this->paginate($this->Posts);
$this->set(compact('posts'));
}
The retrieved values will be displayed in order of decreasing ID (asc).
ID in descending order.
Check the contents of the $posts value in dd($posts).
0 => App\Model\Entity\Posts {#163 ▼
#_accessible: array:6 [▶]
#_fields: array:6 [▶]
// ....
id: 1
title: "CakePHP"
user_id: 1
created: Cake\I18n\FrozenTime #1613560300 {#164 ▶}
modified: Cake\I18n\FrozenTime #1613560300 {#195 ▶}
users: array:2 [▼
0 => App\Model\Entity\Slug {#213 ▼
// ...
id: 1
name: "PHP7.2"
[new]: false
// ...
}
1 => App\Model\Entity\Slug {#224 ▼
id: 2
name: "CakePHP4"
// ...
I have tried the following
'order' => [
'Posts.Slugs.id' => 'desc',
],
or
$posts = $this->paginate($this->Posts->find()->order(['Slugs.id']);
How can I get the best results?
So a Post has many Slugs, and when you load posts in the pagination (sorted by some field in the post), you want the slugs in those posts to be ordered by id? You should be able to do this with the queryBuilder parameter in the containment:
$this->paginate = [
'limit' => 10,
'contain' => [
'Slugs' => [
'queryBuilder' => function (Query $q) {
return $q->order(['Slugs.id']);
}
],
],
];

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 resource ignoring given fields

I'm trying to convert a given API response in something easy to work with.
This is what I have so far:
Controller:
public function drive()
{
$optParams = [
'corpora' => 'drive',
'driveId' => env('GOOGLE_DRIVE_ID'),
'includeItemsFromAllDrives' => true,
'supportsAllDrives' => true,
'fields' => 'files(*)'
];
$results = $this->googleDrive->files->listFiles($optParams);
$data = collect($results);
$collection = new FileCollection($data);
dd($collection);
return 'Hi!';
}
FileCollection resource:
public function toArray($request)
{
return [
'data' => $this->collection,
'meta' => ['files_count' => $this->collection->count()],
];
}
File resource:
public function toArray($request)
{
return [
'name' => $this->resource['name'],
'mime' => $this->resource['mimeType'],
'parents' => $this->resource['parents'],
'version' => $this->resource['version'],
'webDownloadLink' => $this->resource['webContentLink'],
'webLink' => $this->resource['webViewLink'],
'modified_at' => $this->resource['modifiedTime'],
'size' => $this->resource['size']
];
}
This is the result I'm getting:
FileCollection {#223 ▼
+collects: null
+collection: Collection {#243 ▶}
+resource: Collection {#243 ▼
#items: array:2 [▼
0 => File {#224 ▼
+resource: Google_Service_Drive_DriveFile {#279 ▶}
+with: []
+additional: []
}
1 => File {#263 ▼
+resource: Google_Service_Drive_DriveFile {#269 ▶}
+with: []
+additional: []
}
]
}
+with: []
+additional: []
}
So as you can see the types of resources are correct, but for some reason the 'meta' in the FileCollection isn't there, nor are the fields in the File resource. All fields are still shown, like 30+ (instead of the 8 requested in the FileResource).
Am I missing something here?
EDIT:
When accessing the collection with the toArray() method ($collection->toArray(null)), I do indeed get the appropriate result:
array:2 [▼
"data" => Collection {#243 ▼
#items: array:2 [▼
0 => File {#224 ▶}
1 => File {#263 ▶}
]
}
"meta" => array:1 [▼
"files_count" => 2
]
]
So how do I make sure now that this collection uses the toArray() of the FileResources? (I'm still getting over 30 fields, instead of 8).
PS: I don't really get why I need to call the toArray(), nowhere in their documentation is it written : https://laravel.com/docs/5.8/eloquent-resources .

Resources