Larvel Update Data from Array with foreachloop - php

Hello There I need Help To Update on Vehicle Wies on Specific Dates.I'm Attaching Form image and Here is my Controller code.
public function add_vehicle_expense(Request $request)
{
$veh = array('veh_reg_num' => $request->veh_reg_num);
foreach ($veh as $data) {
print_r($request->date[$data]);
dd();
$veh = Sale_report::where('date',$request->date[$data])->where('veh_reg_num', $request->veh_reg_num[$data])->update(['diesel_qty'=> $request->qty[$data], 'diesel_rate'=> $request->rate[$data], 'diesel_amount'=> $request->total_amount[$data], 'other_expense'=> $request->other_exp[$data]]);
}
if ($veh) {
return redirect()->back()->with('Data Store Successfully');
}
//$veh = Sale_report::where('date',$request->date)->where('veh_reg_num', $request->veh_reg_num)->update(['diesel_qty'=> $request->qty, 'diesel_rate'=> $request->rate, 'diesel_amount'=> $request->total_amount, 'other_expense'=> $request->other_exp]);
/* foreach ($request->date as $reg_num => $key ) {
$s = Sale_report::where('date',$request->date[$reg_num])->where('veh_reg_num',$request->veh_reg_num[$reg_num])->first();
$s->diesel_qty = $request->qty[$reg_num];
$s->diesel_rate = $request->rate[$reg_num];
$s->diesel_amount = $request->total_amount[$reg_num];
$s->other_expense = $request->other_exp[$reg_num];
$s->update();
} */
}
I have try to Update Data by matching Each Vehicle Number with Date Some times it Show ErrorException Attempt to read property on int,ErrorException Undefined array key "data"

I have Found The Solution of this Problem.
I've use implode(',' , $request->veh_reg_num) Then I use $datas = explode() function then I use foreach() With exploded Vairable as foreach($datas as $data => $value){
match the each row that with $data array then I Update the values to data base }

Related

Is there a way to store fake attributes as an array instead of JSON?

I am using Laravel Backpack's fake field attribute to store clicked checkboxes into the database. But I don't want it stored as JSON but as an array for example:
Not:
{ "key" : "value }
But as:
[ "value" ]
Here is more context:
https://backpackforlaravel.com/docs/5.x/crud-fields#optional-fake-field-attributes-stores-fake-attributes-as-json-in
Here is an example code snippet
protected function setupUpdateOperation()
{
// The data for the checkboxes values
$roles = Role::all();
foreach ($roles as $role) {
CRUD::field('checkbox_' . $role->id)->type('checkbox')->label($role->description)->fake(true)->store_in('checkboxes_data');
}
}
Let me know if you need more information!
Once you have collection you can simply iterate over it to extract values and store inside a separate array:
$roles = Role::all();
$role_values = [];
foreach($roles as $key => $value) {
$role_values[] = $value;
}
The $role_values will now be a 1-D array containing:
['value 1','value 2', .... , 'value n']
Found it! I just have to override the update method.
For example:
public function update($id)
{
// Logic after update is done.
}

Laravel chunk Call to a member function groupBy() on my variable

In my Laravel 8 project I'm dispatching a Job which runs and collects a bunch of data from the database, the data could be any amount ranging from a few hundred rows of data to potentially thousands, so could be quite memory intensive.
Upon returning the results, they're processed and added to a database table, and I'm hoping to have some kind of progress indication as a percentage that can be reported back to the user whilst the chunking is in progress, I have two tables, a reports and a reports_data table.
I've switched by query over to Laravel's chunk method, and am splitting the data collection into smaller bits as this should improve performance, but for some reason, to use my data as a whole, as if it were a collection I'm pushing it into an empty array called $res, but I'm getting an error so my job failsError: Call to a member function groupBy() on array:
Error: Call to a member function groupBy() on array
I'm wondering what I'm missing...
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$filters = json_decode($this->report->discovery_filters);
$data = [];
// create
foreach ($filters as $findable) {
$resultData = [];
// query data
if (isset($findable->query)) {
$this->setDynamicChartOptions();
$res = [];
$chunkData = DB::table($findable->query->table)
->select($findable->query->columns)
->where($findable->query->filterBy)
->orderBy($findable->query->orderBy->field, $findable->query->orderBy->direction)
->chunk(100, function ($chunkedResults) use ($res) {
foreach ($chunkedResults as $chunk) {
// how to update some kind of progress?
array_push($res, $chunk);
var_dump(count($res));
}
});
// $res expected as a collection? Maybe I can use the `collect` method?
if (isset($findable->query->useGrouping) && $findable->query->useGrouping) {
$results = $res->groupBy(function ($item, $key) use ($findable) {
$date = Carbon::parse($item->{$findable->query->groupBy});
return $date->format($findable->query->groupByFormat);
});
$results = $results->map(function ($item, $key) {
return $item[0];
});
$resultData = $results->flatten();
}
}
$res = [
'componentID' => $findable->componentID ?? 0,
'type' => $findable->type ?? '',
'name' => $findable->name ?? '',
'labelsKey' => $findable->query->labelsKey ?? '',
'dataKey' => $findable->query->dataKey ?? '',
'data' => $resultData ?? [],
'structure' => $this->getStructure($findable, $resultData)
];
array_push($data, $res);
}
// create our report data entry
$this->createReportData($data);
}
UPDATE:
I've tried chunking and grouping, the job fails:
$res = [];
$chunkData = DB::table($findable->query->table)
->select($findable->query->columns)
->where($findable->query->filterBy)
->orderBy($findable->query->orderBy->field, $findable->query->orderBy->direction)
->chunk(100, function ($chunkedResults) use ($res) {
$res[] = $chunkedResults;
foreach($res as $chunk) {
$chunk->groupBy();
}
});
This also fails...
res = [];
$chunkData = DB::table($findable->query->table)
->select($findable->query->columns)
->where($findable->query->filterBy)
->orderBy($findable->query->orderBy->field, $findable->query->orderBy->direction)
->chunk(100, function ($chunkedResults) use ($res) {
$res[] = $chunkedResults;
});
foreach($res as $chunk) {
$chunk->groupBy();
}
And this too, still doesn't seem to work in that it doesn't give back any collection, which is what I need for the rest of my code to work:
$res = [];
$chunkData = DB::table($findable->query->table)
->select($findable->query->columns)
->where($findable->query->filterBy)
->orderBy($findable->query->orderBy->field, $findable->query->orderBy->direction)
->chunk(100, function ($chunkedResults) use ($res) {
foreach ($chunkedResults as $key => $chunk) {
array_push($res, $chunk);
}
});
$res = collect($res);
Because $res = []; is an array, not an instance of eloquent's Illuminate\Support\Collection. Therefore, you can not call $res->groupBy(), as you are trying within the first if-statement.
Remove the ->chunk() method and get your data-chunk by using slice instead for example within a loop that always takes a slice of the data.
Optionally, call collect($res) to turn the array back into a collection. However, when having a Collection already, there is no point in making it into an array first just to cast it back directly afterwords. So I would go with the slice approach.
You could also - withing your chunk callback - do the following:
->chunk(100, function ($chunkedResults) use ($res) {
$res[] = $chunkedResults;
});
And then:
foreach($res as $chunk) {
$chunk->groupBy();
}

Dynamic Create $input in Laravel Controller to Insert data into table ( Error due to Foreach loop not working properly)

Respected Sir/Ma'am, I have different product and I want to create a dynamic $input in controller to save product information into database
Example
$imput['name'] = $request->get('name');
$imput['price'] = $request->get('price');
$imput['description'] = $request->get('description');
To create above input dynamically in controller I try to use foreach loop and pass Input key and value from Frontend side
Example
[["name", "biryani"], ["size", "full"], ["price", "200"], ["description", "chicken + rice"], ["url",
…],…]
0: ["name", "biryani"]
1: ["size", "full"]
2: ["price", "200"]
3: ["description", "chicken + rice"]
4: ["url",…]
5: ["modelName", "chickenBiryani"]
Code i write in controller
(where i do mistake , this code not working also please give answer which I mention in below code comment , Thank You)
public function upload($productInfo)
{
$input=[];
foreach ($productInfo as $data) {
// return $productInfo -- this return data
// return $data -- this return throw error , why this happen
foreach ($data as $val) {
// return $val -- this return data
if ($val[0] == 'modelName') {
$modelName = '\\App\\' . $val[1];
} else {
$input[$val[0]] = $val[1];
}
}
}
$model = new $modelName;
$model::create($input);
return response()->json(['msg' => 'Profile Image Upload Succeessfully']);
}
Please help me sir i am new in Laravel
In your code, you declared $input = [], but using $imput in the loop. That means $input will always be an empty array.
Secondly, Model::create() accepts a single associative array, not multidimensional array e.g:
[
"name" => "Name",
"user_id" => 23
]
Finally, you might need to fletch out your code to eliminate that double loop. But I'm not sure what you're trying to achieve, so can't suggest edits

My Array inside a foreach loop is not accepting a variable in PHP & Laravel

I have a Category array that I'm looping through and counting the subcategories that have their Category ID as the ID of the current item in the loop. It is retrieving the county just fine, uynfportunately when adding to the array it adds the value of zero. When echoed out, the values are as they should be, its only when inserting into the array the value becomes a zero.
This is the code I'm working with in PHP. I am using the Laravel framework.
public function index()
{
$categories = $this->categories->get()->toArray();
$categories_array = array();
$stats = array();
// dd($categories);
foreach ($categories as $key => $value)
{
$subcats_number = sub_categories::whereCategory_id($value['id'])->count();
$stats = array_add($stats, 'subcategories', $subcats_number);
echo $subcats_number.'<br/>';
$listings = classifieds::whereCategory_id($value['id'])->count();
$stats = array_add($stats, 'listings', $listings);
$categories_array = array_add($categories_array, $value['name'], $stats);
}
dd($categories_array);
// return view('admin.categories', compact('categories_array'));
}
The result of my dd:
Dump Result
I am not sure that array_add() helper is appropriate for your function here. As the doc says "The array_add function adds a given key / value pair to the array if the given key doesn't already exist in the array", and I am not sure that this is the proper behavior you need.
I would rather use a simple array_push() here:
public function index()
{
$categories = $this->categories->get()->toArray();
$categories_array = array();
foreach ($categories as $key => $value)
{
$subcats_number = sub_categories::whereCategory_id($value['id'])->count();
$listings = classifieds::whereCategory_id($value['id'])->count();
$stats = array('subcategories' => $subcats_number,'listings' => $listings);
array_push($categories_array,$value['name'] => $stats);
}
dd($categories_array);
}
Otherwise, you should also declare the $stats array into your loop if you choose to keep the array_add() function...

PhP Associative Array displayed in a Table

I am VERY new to PhP. Quick question that I am having trouble finding the answer to online, although I am sure most of you will quickly know the answer. I have the following code creating an associative array and then I am trying to display it in a table. I know there are easier ways to display it in a table like a foreach loop, but I would like to learn this method first :
class CarDealer extends Company {
var $navbar_array = array();
function create_navbar_array ( ) {
$mainurl = $this->company_url; // get the main url address of this web page
$this->navbar_array = array( "Home Page"=>"$mainurl?whichpage=home", "Sales"=>"$mainurl?whichpage=sales",
"Support" => "$mainurl?whichpage=support", "Contacts" => "$mainurl?whichpage=contact" );
}
function getLeftNavBar() {
$data ="<table border='1' style='background-color:yellow; width:35%'>";
$data .="<tr><td>$this->navbar_array['Home Page']</td></tr>";
$data .="<tr><td>$this->navbar_array['Sales']</td></tr>";
$data .="<tr><td>$this->navbar_array['Support']</td></tr>";
$data .="<tr><td>$this->navbar_array['Contacts']</td></tr>";
$data .="</table>";
return $data;
}
}
Later in my code I create an object for my class and then try to print the table. Unfortunately I am just getting an output of things like Array['Home Page'].
$carobject = new CarDealer();
$carobject->create_navbar_array();
print $carobject->getLeftNavBar();
you need to pass array values to the function try
class extends Company {
var $navbar_array = array();
function create_navbar_array ( ) {
$mainurl = $this->company_url; // get the main url address of this web page
$this->navbar_array = array( "Home Page"=>"$mainurl?whichpage=home", "Sales"=>"$mainurl?whichpage=sales",
"Support" => "$mainurl?whichpage=support", "Contacts" => "$mainurl?whichpage=contact" );
return $this->navbar_array;
}
function getLeftNavBar($arr) {
$data ="<table border='1' style='background-color:yellow; width:35%'>";
$data .="<tr><td>".$arr['Home Page']."</td></tr>";
$data .="<tr><td>".$arr['Sales']."</td></tr>";
$data .="<tr><td>".$arr['Support']."</td></tr>";
$data .="<tr><td>".$arr['Contacts']."</td></tr>";
$data .="</table>";
return $data;
}
}
$carobject = new CarDealer();
$arr = $carobject->create_navbar_array();
print $carobject->getLeftNavBar($arr);
or need to make public your array
public $navbar_array = array();
before return $data;, print_r($data); so you can know the associative array's structure. If it didnt print on the page, try looking in view-page-source. You'll get an clear picture. I think $data should be an array, so prob it should be like
$data['someField'] = $someValues;
And, Create or define the array before you use them.
You need to concatenate the array values inside the getLeftNavBar() method so php knows to parse them.
try
$data .="<tr><td>{ $this->navbar_array['Home Page'] }</td></tr>";
or
$data .="<tr><td>".$this->navbar_array['Sales']."</td></tr>";
Why not just call create_navbar_array() inside getLeftNavBar()
function getLeftNavBar() {
$this->create_navbar_array();
.....
You could rewrite it like this
class CarDealer {
private function getUrls() {
return array(
"Home Page" => "$this->company_url?whichpage=home",
"Sales" => "$this->company_url?whichpage=sales",
"Support" => "$this->company_url?whichpage=support",
"Contacts" => "$this->company_url?whichpage=contact"
);
}
public function getLeftNavBar() {
$data ="<table border='1' style='background-color:yellow; width:35%'>";
foreach($this->getUrls() as $url ) {
$data .="<tr><td>".$url."</td></tr>";
}
return $data . "</table>";
}
}
$carobject = new CarDealer();
print $carobject->getLeftNavBar();

Categories