I am having this issue when ever I save to the database the row gets duplicated even if the array contains one index position. Am I missing something here?
foreach($params['service'] as $key => $value){
$data['name'] = $value;
$data['price'] = $params['price'][$key];
$data['business_id'] = $params['business_id'];
$service = new Service($data);
$service->save();
}
data of $params
array:5 [▼
"business_id" => "1"
"service" => array:1 [▼
0 => "web development"
]
"price" => array:1 [▼
0 => "R4500"
]
"submit" => null
]
these are the duplicates
1 web development R4500 1 2018-08-30 07:24:34 2018-08-30 07:24:34
2 web development R4500 1 2018-08-30 07:24:34 2018-08-30 07:24:34
unfortunately the answer provided by #Rathod also produces duplicates but I noticed that when I add multiple data to the array as shown below it saves without duplicates.
array:5 [▼
"business_id" => "1"
"user_id" => "1"
"service" => array:3 [▼
0 => "web development"
1 => "mobile development"
2 => "internet marketing"
]
"price" => array:3 [▼
0 => "R4500"
1 => "R8900"
2 => "R5600"
]
"submit" => null
]
here's the full function
public function createService(array $params) : Service
{
// dd($params);
try {
foreach($params['service'] as $key => $value){
$service = new Service();
$service->service = $value;
$service->price = $params['price'][$key];
$service->business_id = $params['business_id'];
$service->save();
}
return $service;
} catch (QueryException $e) {
throw new CreateServiceInvalidArgumentException($e->getMessage(), 500, $e);
}
}
Try following simple way:
foreach($params['service'] as $key => $value){
$service = new Service();
$service->name = $value;
$service->price = $params['price'][$key];
$service->business_id = $params['business_id'];
$service->save();
}
I hope it works fine.
Those moments I want to slap myself for being stupid... I just noticed I was sending the same data via ajax.. I must have forgotten I had done that.Thanks a lot to everyone for taking your time to look at this for me.
Related
i have form to make a bill for multiple products,
that form return request like this
#parameters: array:5 [▼
"quantity" => array:2 [▼
0 => "1"
1 => "2"
]
"product" => array:2 [▼
0 => "Mr. Jasen Beer,OliveDrab,XS"
1 => "Carlotta Yundt"
]
"date" => array:2 [▼
0 => "2019-12-29"
1 => "2019-12-29"
]
"id" => array:2 [▼
0 => "15"
1 => "11"
]
]
}
i need to loop all arrays to make insert all at once
thanks.
Try to loop it like this, you will get the array wrap every product's attributes:
$inserted_array = [];
foreach($parameters as $key => $values) {
foreach($values as $index => $val) {
$inserted_array[$index][$key] = $val;
}
}
\DB::table('table_name')->insert($inserted_array);
And I found that there is id in your array, remember to make it fillable.
I have a session to save cart info in laravel like this:
$item = [
'id' => 1,
'product_id' => 11
];
$item2 = [
'id' => 2,
'product_id' => 22
];
\Session::push('cart', $item);
\Session::push('cart', $item2);
Now I want delete an Item in array for $id=1:
foreach(\Session::get('cart') as $cart)
{
if($id==$cart['id'])
{
echo 'done';
\Session::forget('cart.' . $i);
}
$i++;
}
It print done but it can not delete that item in list.
what is my wrong?
also I try \Session::pull('card.id', $id);
EDIT
with dd(\Session::get('cart'))
array:4 [▼
2 => array:5 [▼
"id" => 1
"product_id" => "11"
]
3 => array:5 [▶]
4 => array:5 [▶]
5 => array:5 [▶]
]
So I try change the code to this:
foreach(\Session::get('cart') as $key->$cart)
{
if($id==$cart['id'])
{
\Session::forget('cart.' . $key);
}
}
But It can not delete too
I'm pretty sure that cart.{$id} is not a session key, as you're only explicitly setting cart, which is an array. This should work for you instead:
$id = 1; // set from request, etc.
$cartSession = session()->get("cart");
foreach($cartSession AS $index => $cart){
if($index == $id){
unset($cartSession[$index]);
}
}
session()->put("cart", $cartSession);
Essentially, you pull the session to a variable (array), loop that and unset where $index matches $id, then set the remaining array back as "cart".
Note: I'm using session() instead of \Session, which is just Facade vs global function; shouldn't make a difference on which you use, unless below a certain Laravel version (< 5.0 I believe)
Following is the array in the collection:
array:1 [▼
"online" => array:2 [▼
"IS-003" => array:19 [▼
"product" => Product {#831 ▶}
"quantity" => 1
"payment-option" => "online"
]
"HA4" => array:19 [▼
"product" => Product {#822 ▶}
"quantity" => 1
"payment-option" => "online"
]
]
]
Whenever a user changes the payment-option, accordingly the above array should change.
For instance, if HA4['payment-option'] is changed from online to cod, then there should be 2 arrays in parent array.
Following is the array that I want as result.
array:2 [▼
"online" => array:1 [▼
"IS-003" => array:19 [▼
"product" => Product {#831 ▶}
"quantity" => 1
"payment-option" => "online"
]
]
"cod" => array:1 [▼
"HA4" => array:19 [▼
"product" => Product {#822 ▶}
"quantity" => 1
"payment-option" => "cod"
]
]
]
The thing that I have tried so far but couldn't get the desired result:
$paymentOptionCart = collect();
foreach ($cart as $paymentType => &$details) {
foreach ($details as $c => $p) {
if ($c == $code) {
$details[$c]['payment-option'] = $request->option;
$paymentOptionCart->put($paymentType, $details);
unset($details[$c]);
}
}
}
On executing the above code, nothing happens except the payment-option is updated to cod.
I know I am making a silly mistake somewhere, but I am unable to locate where and how.
Can anybody help me out?
This should do your task:
$array = [
"online" => [
"IS-003" => [
"quantity" => 1,
"payment-option" => "online"
],
"HA4" => [
"quantity" => 1,
"payment-option" => "online"
]
]
];
$code = "HA4";
$request_option = "cod";
foreach ($array as $paymentType => $details) {
foreach ($details as $c => $p) {
if ($c == $code) {
$array[$request_option][$c] = $p;
$array[$request_option][$c]["payment-option"] = $request_option;
unset($array[$paymentType][$c]);
}
}
}
unset($details[$c]) seems to be the problem... this punches out the element at index 0, at the end of the first iteration - and index 1 should then become index 0, which subsequently will not be accessible at index 1, during the next iteration of the loop. just run the loop until the exit condition is met and then unset them all, not during the loop... or loop backwards, in order to keep the indexes intact; this would unset the last one element at first and the loop would not exceed the array boundaries.
having two different payment options within a single online order is rather an unlikely example, haven't seen this yet. people might rather post two orders (which implies, not only the business logic is flawed, but the array structure has an unfortunate design, which requires such messing around).
xdebug is great for understanding what is happening. even if my answer might not answer the question in code one can copy & paste (that's not my job), xdebug will tell you exactly what the problem is.
I have been stuck with this problem for quite some time now. I have this particular array with the help of laravel's Socialite.
"first_name" => "xxx"
"last_name" => "xx"
"email" => "xxx#gmail.com"
"work" => array:2 [▼
0 => array:4 [▼
"employer" => array:2 [▼
"id" => "xxxxxxxxxxxxxx"
"name" => "FBI"
]
"location" => array:2 [▶]
"start_date" => "0000-00"
"id" => "496298904045521"
]
1 => array:6 [▶]
]
What I wanted to do is to get the first_name, last_name,email and the name from work and save it in the database after. The problem is I can't seem to retrieve the name of work but instead gives me this error message
(1/1) ErrorException
Undefined index: employer
How can I make this work? Quite lost here.
Controller
public function handleProviderCallback()
{
$usersocialite = Socialite::driver('facebook')->fields([
'first_name', 'last_name', 'email', 'work'
])->user();
//dd($usersocialite);
$findUser = Fbuser::where('email',$usersocialite->email)->first();
if ($findUser) {
Auth::login($findUser);
return view('home');
}else{
$user = new Fbuser;
$user->first_name = $usersocialite->user['first_name'];
$user->last_name = $usersocialite->user['last_name'];
$user->email = $usersocialite->user['email'];
$work=$usersocialite->user['work'];
$w = collect([$work=>[$usersocialite->user['employer']=>[$usersocialite->user['name']]]]);
$flattened = $w->flatten();
$flatten->all();
$user->work = $usersocialite->user[$flatten];
$user->save();
Auth::login($user);
return view('home');
}
}
you are accessing employer name in wrong way. you skip some indexes:
$w = collect([$work=>[$usersocialite->user['work'][0]['employer']=>[$usersocialite->user['work'][0]['employer']['name']]]]);
I can not understand what are you doing really. but I think you want something like this:
$w = collect(['work'=>[$work[0]['employer']=>[$work][0]['employer']['name']]]]);
To access the work name in the multidimensional array you can use something like this:
$user->work = $usersocialite->user['work'][0]['employer']['name'];
or you can use the Laravel helper function array_get:
$user->work = array_get($usersocialite->user, 'work.0.employer.name');
The line above will replace the code:
$work=$usersocialite->user['work'];
$w = collect([$work=>[$usersocialite->user['employer']=>[$usersocialite->user['name']]]]);
$flattened = $w->flatten();
$flatten->all();
$user->work = $usersocialite->user[$flatten];
I'm trying to store values in an array structured like this:
{"parent":
{"class":"Green","user_name":"Nitish","user_loc":"Delhi","user_id":1,"user_blockclass":null,
"child":[
{"class":"Green","user_name":null,"user_loc":null,"user_id":1,"user_blockclass":"fst",
"child":[
{"class":"Green","user_name":"pandey","user_loc":"sdgfsjd","user_id":6,"user_blockclass":"fst"},
{"class":"Green","user_name":"chaku","user_loc":"sdgjs","user_id":7,"user_blockclass":"snd"},
{"class":"Green","user_name":"iks","user_loc":"sjkdfhkjs","user_id":8,"user_blockclass":"trd"},
{"class":"Green","user_name":"yash","user_loc":"hfksjdhfk","user_id":9,"user_blockclass":"frt"},
{"class":"Green","user_name":"joshi","user_loc":"dsfh","user_id":10,"user_blockclass":"fth"}
]},
{"class":"Green","user_name":null,"user_loc":null,"user_id":1,"user_blockclass":"snd",
"child":[
{"class":"Green","user_name":"pandey","user_loc":"sdgfsjd","user_id":6,"user_blockclass":"fst"},
{"class":"Green","user_name":"chaku","user_loc":"sdgjs","user_id":7,"user_blockclass":"snd"},
{"class":"Green","user_name":"iks","user_loc":"sjkdfhkjs","user_id":8,"user_blockclass":"trd"},
{"class":"Green","user_name":"yash","user_loc":"hfksjdhfk","user_id":9,"user_blockclass":"frt"},
{"class":"Green","user_name":"joshi","user_loc":"dsfh","user_id":10,"user_blockclass":"fth"}
]},
]
}
}
I'm trying to place this in two different array and the joining them, but it is not getting the approrpiate result, I've used a variable which iterates to store the different values, if I don't use iteration it overlaps the values and only shows the last stored values. Following is my code:
$blockclass = ['fst', 'snd', 'trd', 'frt', 'fth'];
$i = 0;
$children = $user->relations()->wherePlanId($selectplan)->get();
foreach($children as $ch)
{
$j = 0;
$subuserinfo = [];
$parent_id = $ch->pivot->child;
$subuser = User::find($ch->pivot->child);
$subuserinfo['class'] = "Green";
$subuserinfo['user_name'] = $ch->name;
$subuserinfo['user_loc'] = $ch->city;
$subuserinfo['user_id'] = $ch->id;
$subuserinfo['user_blockclass'] = $blockclass[$i];
if($subuser){
$subchildren = $subuser->relations()->wherePlanId($selectplan)->get();
foreach($subchildren as $subchild)
{
$subsubuser = User::find($subchild->pivot->child);
$subsubuserinfo['class'] = "Green";
$subsubuserinfo['user_name'] = $subsubuser->name;
$subsubuserinfo['user_loc'] = $subsubuser->city;
$subsubuserinfo['user_id'] = $subsubuser->id;
$subsubuserinfo['user_blockclass'] = $blockclass[$j];
$subuserinfo['child'][$i][$j++] = $subsubuserinfo;
}
}
else
{
$subuserinfo['child'][$i][$j++] = NULL;
}
$userinfo['child'][$i++] = $subuserinfo;
}
$tree = $userinfo;
dd($tree);
Currently the data structure which I'm getting is in following format:
array:6 [▼
"class" => "Green"
"user_name" => "Nitish"
"user_loc" => "Delhi"
"user_id" => 1
"user_blockclass" => null
"child" => array:4 [▼
0 => array:6 [▼
"class" => "Green"
"user_name" => null
"user_loc" => null
"user_id" => 1
"user_blockclass" => "fst"
"child" => array:1 [▼
0 => array:5 [▼
0 => array:5 [▼
"class" => "Green"
"user_name" => "pandey"
"user_loc" => "sdgfsjd"
"user_id" => 6
"user_blockclass" => "fst"
]
1 => array:5 [▼
"class" => "Green"
"user_name" => "chaku"
"user_loc" => "sdgjs"
"user_id" => 7
"user_blockclass" => "snd"
]
2 => array:5 [▼
"class" => "Green"
"user_name" => "iks"
"user_loc" => "sjkdfhkjs"
"user_id" => 8
"user_blockclass" => "trd"
]
]
]
]
1 => array:6 [▶]
2 => array:6 [▶]
3 => array:6 [▶]
I'm not able to fetch the data in this format, also after this I want to place the data to be used as json format. Help me out.
I thinkyou should replace all $subuserinfo['child'][$i][$j++] = $subsubuserinfo; with $subuserinfo['child'][$j++] = $subsubuserinfo;
I see you are using Laravel? If you use return response()->json($tree); it will print JSON.
If you also want the parent in front of the JSON you can use this:
return response()->json(['parent' => $tree]);