Add to each array element another element php - php

I'm having one more problem in the logical realm.
I have an array containing ids:
$product_ids = ['1', '5', '3']; <- Example
Another string that I convert to an array separating it by commas, this to indicate the quantities of the products to be withdrawn. For example for product 1 I want 3 drives so I would need the array element to be "1,3".
$finalarray = ["1,3", "5,2", "3,10"];
Next I indicate the code that is executed in the controller (where is what I previously told):
public function ordenform(Request $request)
{
$input = $request->all();
$request->validate([
'nombre' => 'required|string',
'apellido' => 'required|string',
'productos' => 'required',
'cantidades' => 'required|string',
'enviosino' => 'required|in:si,no',
]);
// Quantity Array
$cantidades = explode(',', $input['cantidades']);
if (count($cantidades) != count($input['productos'])) {
return back()->withErrors(['Las cantidades no corresponden a los productos agregados']);
}
$total = 0;
$ganancia = 0;
foreach ($input['productos'] as $producto) {
$producto = Product::find((int) $producto);
$total += $producto->value;
$ganancia += $producto->ganancia;
$producto->stock = (int) $producto->stock - 1;
$producto->save();
}
if ($input['enviosino'] == 'si') {
$total += (int) $input['envio'];
}
if ($input['envio'] == null) {
$input['envio'] = 0;
}
// Products IDS Array
$jsonproductos = json_encode($input['productos']);
Order::create([
'nombre' => $input['nombre'],
'apellido' => $input['apellido'],
'product_ids' => $finalprods,
'value' => $total,
'ganancia' => $ganancia,
'envio' => $input['envio'],
]);
$caja = Config::where('id', 1)->get()->first();
$caja->dinerototal += $total;
$caja->gananciatotal += $ganancia;
$caja->save();
return back()->with('success', 'Orden creada correctamente');
}
Finally, I need to pass as creation parameter the final array to the column products_ids (later I will modify the name).
Another option I thought of is passing objects to an array:
[{id: 1, quantity: 3}]
But I don't know how to get to create that object, I'm still kind of new hehe.
I hope I have explained myself well, English is not my native language. I'm sorry.
I am attentive to your comments !! Greetings.
PS: I am using Laravel

To achieve [{id: 1, quantity: 3}] there will be several idea, but it seems to be an arrayList, so below is how you can create an arrayList in PHP. I have not tested the code, just written here, but should give you the idea to achieve this.
I am considering one is Order class.
<?php
class Order {
private $id;
private $quantity;
public function setId(int $id) {
$this->id = $id;
return $this;
}
public function getId(){
return $this->id;
}
public function setQuantity(int $quantity) {
$this->quantity = $quantity;
return $this;
}
public function getQuantity(){
return $this-> quantity;
}
public function toArray(){
return [
'id' => $this->getId(),
'quantity' => $this->getQuantity()
];
}
}
?>
another is OrderList.
<?php
class OrderList {
private $orderList;
public function __construct(Order ...$orders) {
$this->orderList = $orders;
}
public function toArray(){
$arr = [];
foreach ($this->orderList as $order) {
$arr[] = $order->toArray();
}
return $arr;
}
}
?>
and then use like
$order1 = new Order();
$order1 = $order1->setId(1)->setQuantity(10);
$order2 = new Order();
$order2 = $order1->setId(2)->setQuantity(20);
$orderList = new OrderList($order1, $order2);
var_dump(json_encode($orderList->toArray()));
//Output
string(47) "[{"id":2,"quantity":20},{"id":2,"quantity":20}]"
You do not need json_encode, I have added it to print only.

Nevermind, resolved ->
$prodsfinal = array();
for ($i = 0; $i < sizeof($cantidades); $i++) {
$array = [
'id' => json_decode($input['productos'][$i]),
'cantidad' => (int) $cantidades[$i],
];
array_push($prodsfinal, $array);
}

Related

How to loop foreach in laravel dynamically

Am just learning Laravel and I have this logic were in I want to display array of total items based from user, to explain this further here is my database
user table
items table
this is my current code
public function display()
{
$users = User::where('type', 'Shop')->get();
foreach($users as $user){
$shop_id = $user['id'];
$shop_name = $user['name'];
}
$total = Item::where('user_id', $shop_id)->sum('total');
$shops =[
['Name' => $shop_name, 'total' => $total],
];
return response()->json([
"shops" =>$shops
], 200);
}
and here is my sample output:
am only getting 1 object instead of 2 as I have two shops how to loop this dynamically.
thanks
the $shops and $total variable is not in foreach loop that's because it returns only one row. and you must use $shops[] .
public function display()
{
$users = User::where('type', 'Shop')->get();
foreach($users as $user){
$shop_id = $user['id'];
$shop_name = $user['name'];
$total = Item::where('user_id', $shop_id)->sum('total');
$shops[] =['Name' => $shop_name, 'total' => $total];
}
return response()->json([
"shops" =>$shops
], 200);
}
but the best and clean way is to use laravel relationship
in User model:
public function items()
{
return $this->hasMany(Item::class) ;
}
and display controller :
public function display()
{
$shops = User::where('type', 'Shop')->get()
->mapWithKeys(function($user){
return ['name'=>$user->name ,
'total'=> $user->items->sum('total')
]});
return response()->json(["shops" =>$shops], 200);
}
Do this
$shops[] = ['Name' => $shop_name, 'total' => $total];
to push all the shops into one array.
You are currently overriding the hole array.
UPDATE: Also move the sql part into the foreach:
foreach($users as $user){
$shop_id = $user['id'];
$shop_name = $user['name'];
$total = Item::where('user_id', $shop_id)->sum('total');
$shops[] =['Name' => $shop_name, 'total' => $total];
}

set a variable that holds array from a function

Is this a correct syntax or correct approach?
function formGroups($forms)
{
$g_education = $form->groups()->create(['name' => 'Education']);
$g_engagement = $form->groups()->create(['name' => 'Engagement in early childhood education']);
return[$g_education, $g_engagement];
}
private function forms()
{
$form = $this->period('B4 school', 5, 'year', 1, 'year')->periodDomains()->create(['domain_id' => $this->domains()->getKey()]);
return $form;
}
protected function test($formGroup)
{
return $this->$formGroup;
}
$form = $this->forms(); //passing the forms() value to $form
$formGroup = array($this->formGroups($form));
$this->educations($formGroup);
$this->engagements($formGroup);
I wanted to pass the value to $formGroup so that I can use the values from the other classes. I am currently getting an error while doing it. Is this the right syntax?

How to store session id with request all?

I'm trying to save the passed course_id into lesson form in a DRY format.
I've tried saving each variable individually and it worked, however when I try to DRY up the code it is not working. Here is the code That I've tried.
public function store(StoreLessonsRequest $request)
{
if (! Gate::allows('lesson_create')) {
return abort(401);
}
$request = $this->saveFiles($request);
$lesson = Lesson::create($request->all() +
$lesson->course_id = session()->get('id') +
+ ['position' => Lesson::where('course_id', $request->course_id)->max('position') + 1]);
foreach ($request->input('lesson_materials_id', []) as $index => $id) {
$model = config('medialibrary.media_model');
$file = $model::find($id);
$file->model_id = $lesson->id;
$file->save();
}
return redirect()->route('admin.exams.create', ['course_id' => $request->course_id]);
}
I expected the course_id to save, but is giving me an error of Unsupported operand types.
Here is how I finally solved it. First I've declared the variable then I've passed it through.
public function store(StoreLessonsRequest $request)
{
if (! Gate::allows('lesson_create')) {
return abort(401);
}
$request = $this->saveFiles($request);
$seesion = session()->get('id');
$lesson = Lesson::create($request->all()
+ ['position' => Lesson::where('course_id', $request->course_id)->max('position') + 1] + ['course_id' => $seesion] );
foreach ($request->input('lesson_materials_id', []) as $index => $id) {
$model = config('medialibrary.media_model');
$file = $model::find($id);
$file->model_id = $lesson->id;
$file->save();
}

Laravel Increase SQL speed

I am trying to increase the speed of my queries in Laravel 5.7 and I have the call down to ~2.5 seconds. I am trying to figure out more ways to make it faster and if I could get some help I'd greatly appreciate it.
Thanks
How my data is structured:
Function(Controller):
public function getUserDataTmp(Request $request) {
$input = file_get_contents("php://input");
$request = json_decode($input);
if ($this->authTokenAccess($request) == true) {
$bottomWords = bottom_exterior_word::select('word','sentence','sequence','id','group_id')->where('user_id','=', $request->id)->get();
$emergencyWords = left_exterior_word::select('word','sentence','sequence','id')->where('user_id','=', $request->id)->get();
foreach($bottomWords as $tmp => $key) {
$group_id = $key->group_id;
$bottomWords->user_id = $request->id;
$bottomWords[$tmp]->words = $key->getMainWords($group_id, $request->id);
}
foreach($emergencyWords as $key => $word) {
$emergencyWords[$key]->image = imageModel::select('base64','id')->where('emergency_id','=', $word->id)->first();
}
$data = [
'data' => [
'return' => 'success',
'code' => 'VEDC001',
'response' => 'Successfully Gathered Words',
'main_categories' => $bottomWords,
'emergency_words' => $emergencyWords
]
];
return(json_encode($data));
}
}
getMainWords Function(bottom_exterior_word model):
public function getMainWords($group_id, $id)
{
// return("TEST");
$words = \App\main_word::select('id','group_id','sentence','sequence','word')->where('group_id','=', $group_id)->where('user_id','=', $id)->get();
foreach ($words as $key => $word) {
$words[$key]->image = Image::select('base64','id')->where('word_id','=', $word->id)->first();
}
return $words;
}
Start by refactoring so that you dont query inside a foreach loop
foreach($bottomWords as $tmp => $key) {
$group_id = $key->group_id;
$bottomWords->user_id = $request->id;
$bottomWords[$tmp]->words = $key->getMainWords($group_id, $request->id);
}
I would change the getMainWords function to accepts an array of group id's and use the whereIn clause:
The whereIn method verifies that a given column's value is contained
within the given array:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
Same treatment for this loop.
foreach($emergencyWords as $key => $word) {
$emergencyWords[$key]->image = imageModel::select('base64','id')->where('emergency_id','=', $word->id)->first();
}
In general minimizing the NUMBER of queries will improve response time.
Old post, would just like to update it though. Since I have first posted this, I have learned a lot more about Laravel and am a lot more experienced with it.
Here is my new function and solution:
Controller:
public function data(Request $request)
{
return response()->success(
[
'emergencywords' => EmergencyWord::with('image')->whereUserId($request->user()->id)->get(),
'categorywords' => CategoryWord::with(['image','words.image'])->whereUserId($request->user()->id)->get(),
]
);
}
Category Word Relationships:
public function image()
{
return $this->hasOne('App\Image','id','image_id');
}
public function words()
{
return $this->hasMany('App\MainWord','category_words_id','sequence');
}
Emergency Word Relationships:
public function image()
{
return $this->hasOne('App\Image','id','image_id');
}
Main Word Relationships:
public function image()
{
return $this->hasOne('App\Image','id','image_id');
}

Laravel 4 - view is rendered in one function but not in another

Ok here is the test controller:
class TestController extends BaseController {
public function __construct() {
ini_set("display_errors", true);
}
private $turnoverPerFranchise = array(
0 => 't1',
1 => 't2'
);
private $turnoverPerShop = array(
0 => 's1',
1 => 's2'
);
public function getTurnover() {
$formData = array();
$formData['shops'] = 'shosp dropdown';
$form = View::make('test.form', $formData);
$data2['content'] = $form;
return View::make('test/template', $data2);
}
public function postTurnover() {
echo 'post';
$formData = array('a');
$formData['filteredData'] = $this->getFiltered();
// if not set index shops. then it displays error - its how is expected
$data['content'] = View::make('test.form', $formData);
return View::make('test/template', $data);
}
private function getFiltered() {
$data2['totalsTable'] = $this->getTotalsView();
$data2['franchiseBlocks'] = array();
foreach ($this->turnoverPerFranchise as $franchiseId => $franchiseTurnover) {
$franchiseData['franchise'] = $franchiseTurnover;
$franchiseData['systemCurrency'] = '$';
$franchiseData['shopViews'] = array();
foreach ($this->turnoverPerShop as $shopId => $shopTurnover) {
if ($shopTurnover['franchiseId'] == $franchiseId) {
$franchiseData['shopViews'][] = 'shop view';
}
}
$data2['franchiseBlocks'][] = View::make('test.filteredData.franchise', $franchiseData);
//$data2['franchiseBlocks'][] = 'aa';
}
echo count($data2['franchiseBlocks']) . '<br>';
return View::make('test.filteredData.main', $data2); // same
}
/**
* Gets table of filteredData totals
* #return object
*/
private function getTotalsView() {
$dataTotals = array();
$dataTotals['totals'] = 'bla bla bla';
$dataTotals['systemCurrency'] = '$';
return View::make('test.filteredData.totalsTable', $dataTotals);
}
public function getMain() { // works
$data2['franchiseBlocks'] = array(1 => 'a');
return View::make('test.filteredData.main', $data2); // the same view in getFiltered is not displayed
}
}
If I call function postTurnover()
then it is rendered
post2 and the submit button. 2 means that there are 2 items for view to run in foreach loop.
When I run function getMain()
then the view renders perfectly fine.
View test/filteredData/main.blade.php is simple:
<br>
main
#foreach ($franchiseBlocks as $franchise)
<strong>franchise block</strong>
{{ $franchise }}
#endforeach
view test/filteredData/franchise.blade.php
franchise
#foreach ($shopViews as $shop)
<strong>aaa</strong>
#endforeach
Other views are probably not important. But if they are I will copy them.
Can you tell why can it not display as expected?
found the problem - was not using that data in test/filteredData/form.blade.php
had to put:
{{ $filteredData; }}

Categories