How to add value to array without oerwritting and access those values - laravel

Hello I'm trying to add products to a cart without overwritting the previous product added to the cart and without duplicating if the two products are the same but instead increment the quantity by 1.
Here's how i'm setting up my cart and adding products to it:
public function addToCart(Request $request)
{
$id = $request->product_id;
$product = Product::find($id);
$request->session()->put('cart', [
[
"id" => $product->id,
"name" => $product->name,
"price" => $product->price,
"image" => $product->image,
"quantity" => 1,],
]);
$cart = $request->session()->only(['cart']);
dd($cart);
return redirect('cart');
}
And this is what i get from the dd
array:1 [▼
"cart" => array:1 [▼
0 => array:5 [▼
"id" => 1
"name" => "name"
"price" => 42.42
"image" => "../image.jpg"
"quantity" => 1
]
]
]
I tried using put or cart[] = [product infos...] instead of push but it would still overwrite the previous product
Also I'm confused as to how to access each product stored in my cart individually, i can access to the whole cart via $request->session()->only(['cart']) but i can't find how to access the products of that cart.

Well the problem is in here:
$request->session()->put('cart', [
[
"id" => $product->id,
"name" => $product->name,
"price" => $product->price,
"image" => $product->image,
"quantity" => 1,],
]);
You create two arrays. So either change this part to:
$request->session()->put('cart', [
"id" => $product->id,
"name" => $product->name,
"price" => $product->price,
"image" => $product->image,
"quantity" => 1,
]);
or this part:
cart[] = [product infos...]
to
cart[0][] = [product infos...]
but not both.
Also, a better and more used practice is not to store the whole cart in session, but to store it in tables carts and cart_items and to store in session only a hash.

Related

Laravel read value of array inside of array

I diedump this array and there is a number inside data array
^ array:1 [▼
"data" => array:15 [▼
0 => array:15 [▼
"product_name" => "MOBILELEGEND - 86 Diamond"
"category" => "Games"
"brand" => "MOBILE LEGEND"
"type" => "Umum"
"seller_name" => "PT***"
"price" => 19800
"buyer_sku_code" => "ML86"
"buyer_product_status" => true
"seller_product_status" => true
"unlimited_stock" => true
"stock" => 0
"multi" => true
"start_cut_off" => "23:30"
"end_cut_off" => "0:20"
"desc" => "no pelanggan = gabungan antara user_id dan zone_id"
]
1 => array:15 [▶]
2 => array:15 [▶]
]
]
How can I foreach the value inside the number? the number I mean is 0,1,2
You need to use nested foreach to loop through the multidimensional array you have.
let your array be called $arr for example
// $arr = [ 'data' => [ ['name' => 'lorem'], ... ]];
foreach ($arr['data'] as $item) {
foreach ($item as $key => $value) {
// Do whatever you need here...
}
}

Laravel Collections search

I have SQL query & sub query results and then convert these results to collection as bellow
$co=collect($users);
my collection array is as bellow
Illuminate\Support\Collection^ {#1984
#items: array:4 [
"id" => 92
"user" => "abc"
"created_at" => "2020-04-16T12:13:11.000000Z"
"updated_at" => "2020-12-05T20:32:56.000000Z"
"groups" => array:6 [
0 => array:6 [
"id" => 1
"user_id" => 1
"group_id" => 92
"title" => "new group"
"created_at" => "2020-04-16T12:13:11.000000Z"
"updated_at" => "2020-12-05T20:32:56.000000Z"
1 => array:6 [
"id" => 1
"user_id" => 1
"group_id" => 91
"title" => "other group"
"created_at" => "2020-04-16T12:13:11.000000Z"
"updated_at" => "2020-12-05T20:32:56.000000Z"
as you can see there is two columns with name of {id} , one in first array and other in sub array "groups"
I want to search the collection for ID and for title
I am using these command but both are returning empty array.
$filtered = $co->where('id',1);
dd($filtered);
also
$filtered = $co->where('title','new group');
dd($filtered)
;
or
$filtered = $co->where('groups.title','new group');
dd($filtered);
how to get these values
Thanks

values are not being stored correctly in the array $items

I want to get the quantity of each registration type with the code below:
$registrationTypeDetails = Registration::with('participants:id,registration_type_id,registration_id')->find($regID);
$type_counts = [];
foreach ($registrationTypeDetails->participants as $p) {
$name = $p->registration_type->name;
if (!isset($type_counts[$name])) {
$type_counts[$name] = 0;
}
$type_counts[$name]++;
}
The dd($type_counts), if the conference has 2 registration types available (general and plus) and the user is doing a registration with 2 participants in the registration type "general" and 0 participants in the registration type "plus" shows:
array:2 [▼
"general" => 2
]
Then I need to make a post request to an API where is necessary to send in the request body the quantity of each registration type, in this case there is only 1 registration type "general" and the value for quantity should be "2".
So I have this code below the above code to create the array:
foreach ($registrationTypeDetails->participants as $registrationType) {
$items['invoice']['items'][] = [
'name' => $registrationType->registration_type->name,
'unit_price' => $registrationType->registration_type->price,
'quantity' => $type_counts[$registrationType->registration_type->name],
];
}
$create = $client->request('POST', 'https://...', [
'query' => ['api_key' => '...'], 'json' => $items,
]);
But then the output array is:
array:1 [▼
"invoice" => array:4 [▼
"client" => array:7 [▶]
"items" => array:2 [▼
0 => array:5 [▼
"name" => "general"
"unit_price" => 10
"quantity" => 2
]
1 => array:5 [▼
"name" => "general"
"unit_price" => 10
"quantity" => 2
]
]
]
]
Instead of only 1 item:
array:1 [▼
"invoice" => array:4 [▼
"client" => array:7 [▶]
"items" => array:2 [▼
0 => array:5 [▼
"name" => "general"
"unit_price" => 10
"quantity" => 2
]
]
]
]
$items shows:
array:1 [▼
"invoice" => array:4 [▼
"items" => array:2 [▼
1 => array:5 [▼
"name" => "general"
"unit_price" => 10
"quantity" => 2
]
2 => array:5 [▼
"name" => "plus"
"unit_price" => 0
"quantity" => 2
]
]
]
]
You would need to key the results of the items according to the registration type name:
foreach ($registrationTypeDetails->participants as $registrationType) {
$items['invoice']['items'][$registrationType->registration_type->name] = [
'name' => $registrationType->registration_type->name,
'unit_price' => $registrationType->registration_type->price,
'quantity' => $type_counts[$registrationType->registration_type->name],
];
}
Better is to use the id of the registration_type if there is one:
foreach ($registrationTypeDetails->participants as $registrationType) {
$items['invoice']['items'][$registrationType->registration_type->id] = [
'name' => $registrationType->registration_type->name,
'unit_price' => $registrationType->registration_type->price,
'quantity' => $type_counts[$registrationType->registration_type->name],
];
}
Explanation
As you loop over the participants linked to a registration type multiple participants could have the same registration type. So in your case you need to group the results according to registration type. Just adding to items[] appends to the items array. You want to group the results by registration type.
Fixing the 422 validation error
Your items is a valid array, but because it is translated to json the 1 and 1 would be keyed as an object. To force the key adjustment you can do the following:
// It is hacky but it re-keys the items array numerically.
$items['invoice']['items'] = array_values($list['invoice']['items']);

How to get a particular field value from multidimensional array in laravel

I have a variable $cart which stores the details of product. I want to get a particular field from the cart.
dd($cart) show the following result.
Cart {#437 ▼
+items: array:1 [▼
"airports_334_64" => array:4 [▼
"qty" => 1
"price" => 1600000
"duration" => 0
"item" => array:28 [▼
"id" => 64
"created_at" => "2017-05-29 10:24:22"
"updated_at" => "2017-05-29 10:26:51"
"title" => "Airport ad"
"price" => "120000"
"location" => "Airport T3"
"city" => "Delhi"
"state" => "Delhi"
"rank" => "12"
"landmark" => "abc"
"description" => "<p>new</p>"
"image" => "1496053462.jpg"
"references" => ""
"status" => "Available"
"display_options" => null
"light_option" => null
"airportnumber" => null
"discount" => "1"
"slug" => null
"reference_mail" => "chingkhei91#gmail.com"
"airports_id" => "64"
"area" => "arrival_check_in_hall"
"displayoption" => "backlit_panel"
"dimensions" => "7'10"x3'9""
"optionprice" => "1600000"
"units" => "8"
"ad_code" => ""
"variation_id" => 334
]
]
]
+totalQty: 1
+totalPrice: 1600000
}
I want to get the value of reference_mail i.e Cart->items->item->reference_mail
Use the Collections provided by Laravel:
$items = collect($cart->items);
$reference_mails = $items->map(function($item){
return $item['reference_mail'];
});
This leaves you with an array of all the reference mails. The behaviour of map is described here
If you want to access them then you should iterate over the items like so.
foreach ($cart->items as $items) {
foreach ($items as $item) {
$email = $item['item']['reference_mail'];
}
}
If you need to access it directly based on array index then you could do this.
$email = $cart->items['airports_334_64']['item']['reference_mail'];
If you need the list of reference_mail then you do this in your query rather than going through all this. If you have a collection then you can use pluck method to retrieve the list of emails.

How to check if multidimensional array is empty or not in laravel

I'm trying to check if there is an empty array in the nested arrays.
This is what I get from my form.
array:15 [▼
"_token" => "h4aR4xJlWhZveRKbAgHzgzHWSKSqyhVKb7OHAgWH"
"name" => "Test office"
"is_department" => "0"
"hours" => "1-3"
"description" => "Description"
"content" => "<p>Content</p>"
"street" => "123 Street"
"city" => "Foomania"
"state" => "Sweet state"
"postal" => "98234"
"phone" => "5748293212"
"fax" => "2123131233"
"email" => "test#domain.tld"
"additional-page" => ""
"office_fees" => array:4 [▼
0 => array:2 [▼
"description" => ""
"fee" => ""
]
1 => array:2 [▼
"description" => ""
"fee" => ""
]
2 => array:2 [▼
"description" => ""
"fee" => ""
]
3 => array:2 [▼
"description" => ""
"fee" => ""
]
]
]
How can I check if there is empty array in office_fees ?
Just to be clear, office_fees will always return at least one array. What I'm trying to is to be able to determine whether the office_fees need to be saved into another model.
Not sure what You're looking for but:
empty($data['office_fees'])
checks if an array isset and not empty. If You want to check an empty array try this:
if (is_array($data['office_fees']) && !empty($data['office_fees']))
In laravel 5.2 you can validate arrays
$validator = Validator::make($request->all(), [
'office_fees.*.description' => 'required',
]);
Source: Laravel documentation

Resources