create associative array with key and value generated in for - laravel

i´m traying to create associative array, from query in laravel.
public function assignAllCall(Request $request)
{
$callList = [];
$newCall = [];
for($i=0; $i<count($request->get('calls')); $i++){
array_push($callList, Listado::where('id', $request->get('calls')[$i])->get());
}
for($i=0; $i<count($callList); $i++){
for($j=$i; $j<count($callList[$i]); $j++){
$newCall = [
'nomape' => $callList[$i][$j]->nomape,
'direccion' => $callList[$i][$j]->direccion,
'provincia' => $callList[$i][$j]->provincia,
'ciudad' => $callList[$i][$j]->ciudad,
'cp' => $callList[$i][$j]->cp,
'telefono' => $callList[$i][$j]->telefono,
'movil' => $callList[$i][$j]->movil,
'id_teleoperadora' => $request->get('teleoperadora'),
'id_estado' => 1,
'fecha_asignacion' => Carbon::now()->format('Y-m-d H:m:s'),
'created_at' => Carbon::now()->format('Y-m-d H:m:s'),
];
}
print_r($newCall);
// create call
//$result = Llamada::create($newCall);
}
//return $result;
}
i have this function that receive param from ajax and this values it´s ids array.
I need get all data from this ids for get all data and create new calls with this data, for this i have one for to do query and assign to array. after i´m traying to create associative array but when i do print_r always i return same result:
Array
(
[nomape] => x
[direccion] => x
[provincia] => x
[ciudad] => x
[cp] => x
[telefono] => x
[movil] => x
[id_teleoperadora] => x
[id_estado] => x
[fecha_asignacion] => x
[created_at] => x
)
always same value. I don´t know if i do well my function or have one better solution for to do this.
Thanks for read and thanks for help.

Instead of
for($j=$i; $j<count($callList[$i]); $j++){
try this:
for($j=0; $j<count($callList[$i]); $j++){

Related

How to add an array within a foreach in laravel controller?

I am trying to insert data from a form which i get it in the form of an array and i am using a foreach to insert the data each in to the database. amongst these data i have another array that i need to insert it in the form of an array.
The Amendities should be saved in the form of an array! i tried using implode but didn't quite get the results i expected.
foreach ($request->room_type as $item => $v) {
$data2 = array(
'room_type' => $request->room_type[$item],
'no_of_pax' => $request->no_of_pax[$item],
'no_of_pax_children' => $request->no_of_pax_children[$item],
'cost_per_adult' => $request->cost_per_adult[$item],
'cost_per_child' => $request->cost_per_child[$item],
'room_description' => $request->room_description[$item],
'amendities' => implode($request->amendities),
'hotel_id' => $hotel->id,
);
dd($data2);
Rooms::insert($data2);
}
impoding Amendities array saves the data as a string but i am trying to get the values as an array.
u need to prepare a datasets to insert multiple record
so u can try like this
$data2 = [];
foreach ($request->room_type as $item => $v) {
$opt = array(
'room_type' => $request->room_type[$item],
'no_of_pax' => $request->no_of_pax[$item],
'no_of_pax_children' => $request->no_of_pax_children[$item],
'cost_per_adult' => $request->cost_per_adult[$item],
'cost_per_child' => $request->cost_per_child[$item],
'room_description' => $request->room_description[$item],
'amendities' => json_encode($request->amendities),
'hotel_id' => $hotel->id,
);
array_push($data2,$opt);
}
Rooms::insert($data2);
Thank you for the help guys this is final solution which worked for as per your help
foreach ($request->room_type as $item => $v) {
$opt = array(
'room_type' => $request->room_type[$item],
'no_of_pax' => $request->no_of_pax[$item],
'no_of_pax_children' => $request->no_of_pax_children[$item],
'cost_per_adult' => $request->cost_per_adult[$item],
'cost_per_child' => $request->cost_per_child[$item],
'room_description' => $request->room_description[$item],
'amendities' => json_encode($request->amendities),
'hotel_id' => $hotel->id,
);
array_push($data2, $opt);
}
Rooms::insert($data2);
Thank you for your help all of you!

Modify/add/rename eloquent collection

Let's say I've got eloquent collection returns from:
$b = Book::get(); (columns: id, book_name, pages)
$m = Magazine::get(); (columns, id, mag_name, type)
How do I then:
Combine them in the same collection.
Rename ->book_name/mag_name to k
Add type and if book use 'null' as value
add ->hash (str::random)
I want to keep the collection to be able to use the benifits that come with it. ie. not convert it to an array.
Laravel 7
You can do it with collection merge method
$b = Book::get(['id','book_name as k','pages']);
$m = Magazine::get(['id','mag_name as k','type']);
$bb = $b->map(function ($book){
$book['type'] = null;
$book['hash'] = Str::random();
return $book;
});
$mm = $m->map(function ($magzine){
$magzine['hash'] = Str::random();
return $magzine;
});
$merged = $bb->merge($mm);
return $merged;
Assume we have the following collections:
$b = Book::get(); //(columns: id, book_name, pages)
$m = Magazine::get(); //(columns, id, mag_name, type)
Second, update the fields:
$books = $b->map(function ($book) => {
return [
'id' => $book->id,
'k' => $book->book_name,
'type' => null,
'hash' => Str::random()
];
});
$magazines = $b->map(function ($magazine) => {
return [
'id' => $magazine->id,
'k' => $magazine->mag_name,
'type' => $magazine->type,
'hash' => Str::random()
];
});
Third, merge the collections:
$result = $books->merge(magazines);

Inserting and updating records from 3 tables in laravel

I am storing records for my product transfer app using 3 tables in single action. Transferhistories, Warehouse1StockSummaries and Warehouse2StockSummaries.
storing records to trasnferinghistories is ok, and also the increment method I declare to Warehouse2StockSummaries is also working fine except for Warehouse1StockSummaries.
here's my store function,
public function store(Request $request)
{
$input = $request->all();
$items = [];
for($i=0; $i<= count($input['product_id']); $i++) {
// if(empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
if(!isset($input['qty_in'][$i]) || !is_numeric($input['qty_in'][$i])) continue;
$acceptItem = [
'product_id' => $input['product_id'][$i],
'transfer_qty' => $input['qty_out'][$i],
'user_id' => $input['user_id'][$i]
];
array_push($items, Transferhistories::create($acceptItem));
// dd($input);
//update warehouse 1 summary
$warehouse1summary = Warehouse1StockSummaries::firstOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_in'][$i],
'qty_out' => $input['qty_out'][$i]
]);
if (!$warehouse1summary->wasRecentlyCreated) {
$warehouse1summary->increment('qty_out', $input['qty_out'][$i]);
}
//update warehouse 2 summary
$stock2Summary = Warehouse2StockSummaries::firstOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_out'][$i],'qty_out' => null]);
if (!$stock2Summary->wasRecentlyCreated) {
$stock2Summary->increment('qty_in', $input['qty_in'][$i]);
}
}
return redirect()->route('transferHistory.index');
}
updating warehouse 1 summary is not doing what it should be.
any suggestion master? thank you so much in advance!
According to laravel, firstOrCreate does not save the value, so after you do:
$warehouse1summary = Warehouse1StockSummaries::updateOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_in'][$i],
'qty_out' => $input['qty_out'][$i]
]);
Edit
The method firstOrNew will return the first or a instance of the Model.
So what you wanna do is this:
$warehouse1summary = Warehouse1StockSummaries::firstOrNew(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_in'][$i],
'qty_out' => $input['qty_out'][$i]
]);
if(isset($warehouse1summary->created_at)){
$warehouse1summary->qty_out = $warehouse1summary->qty_out + $input['qty_out'][$i];
}
$warehouse1summary->save();

How to validate and insert array of objects in php?

I want to validate and insert array of object into my database. This is my array of objects: (Front end js)
studentData: [
{id: 1, name: 'Juan'},
{id: 2, name: 'Jema'},
]
This is my current code for StudentController.php:
for($i; $i <= count($request->input()); $i++){
$student = Student::create([
'id' => $request[$i]["id"],
'name' => $request[$i]["name"],
]);
}
and this works perfectly when I'm inserting all my object. Now, I want to validate all the request. This code is not working:
$validate = $request[$i]->validate([
'id' => 'required|unique:students|numeric'
]);
for($i; $i <= count($request->input()); $i++){
$validate = $request[$i]->validate([
'id' => 'required|unique:students|numeric'
]); //this is the error. I cant validate the data foreach user
$student = Student::create([
'id' => $request[$i]["id"],
'name' => $request[$i]["name"],
]);
}
You have to do array input validation with dot like this:
$this->validate($request,[
'studentData.*.id' => 'required|unique:students|numeric',
'studentData.*.name' =>'required'
],
$messages = [
// write error messages
]);
I hope you will understand.
You can see laravel docs for array input validation here https://laravel.com/docs/5.6/validation#validating-arrays

Laravel UpdateOR Create not work with relationship

I want to update my related table on laravel 5.4
my code
$id = $request->id;
$find = Presal::find($id);
$find->user_id = $request->customer_id;
$find->proposalid = $request->proposalid;
$psal = $find->save();
if ($psal) {
foreach ($request->service_item_id as $key => $n) {
$find->proposalService()->updateOrCreate([
'service_item_id' => $request->service_item_id[$key],
'start_date' => $request->start_date[$key],
'end_date' => $request->end_date[$key],
'service_type_id' => $request->service_type_id[$key],
'vendor_submit' => $request->vendor_submit[$key],
]);
}
}
Here always my code create a new row in proposalService but not update.
How can I make create if new and Update if exist.
updateOrCreate() takes 2 arguments (2 arrays). First array, you pass the element you want to check, usually the primary key and some other element. It then checks if those elements exist, else, create a new one.
$find->proposalService()->updateOrCreate(
[
'service_item_id' => $request->service_item_id[$key],
'service_type_id' => $request->service_type_id[$key]
],
[
'start_date' => $request->start_date[$key],
'end_date' => $request->end_date[$key],
'vendor_submit' => $request->vendor_submit[$key]
]
);
Here I used service_item_id and service_type_id as first argument to check if they already exist.

Resources