Saving a request variable inside foreach in Laravel store method - php

2 values are collected from the form as variables and rest as array. Then saving the values inside foreach loop in store method.
There is no problem with Array values, but for single variables, the values are showing null for the way I am trying.
I am trying to save $start and $end values inside the foreach loop. The code is below:
$start = $request->start;
$end = $request->end;
foreach ($request->user_id as $key => $val) {
$bill = new UserBill;
if (is_array($request->checked) && in_array($val, $request->checked)) {
$bill->start = $start;
$bill->end = $end;
$bill->amount = $request->amount[$key];
$bill->package = $request->package[$key];
$bill->package_type = $request->package_type[$key];
$bill->user_id = $val;
$bill->save();
}
}
Please help.

You can try sending the information directly to the save method instead populating an object.
foreach ($request->user_id as $key => $val) {
$bill = new UserBill;
if (is_array($request->checked) && in_array($val, $request->checked)) {
$bill->save([
"start" => $request->start,
"end" => $request->end,
"amount" => $request->amount[$key],
"package" => $request->package[$key],
"package_type" => $request->package_type[$key],
"user_id" => $val
]);
}
}
Just make sure all the variables has content. You can check by using the dd() helper
dd($request->toArray()); //toArray() for an easier looking on the output

check your variables are declared in your model in the fillable part https://laravel.com/docs/7.x/eloquent#mass-assignment , also try to put Log to see the values ​​of your variables:
Log::info($start)
Log::info($end)

Related

Removing an associated key/value pair from array (nested)

I have two function to add remove parameters to the query string. The "add_query_params" (thanks to this forum) is working nicely and I can now add multiple tags to the query string of the same type.
For example
http://example.com?tags[]=flowers&tags[]=shrubs&category[]=garden
As you can see, I can add multiple of the same parameters, I am also querying these nicely using queryfilters.
However my newest problem, is simply removing a single tag type without affecting the rest of the query string. I will then rebuild the query without the deleted tag.
Someone kindly yesterday helped me to to a point but this removes ALL tag key values, not just the specified tag.
So if I was to delete say $tags[]shrubs from the above URL it would actually delete BOTH tag[]shrubs AND $tags[]flowers.
This obviously isn't very intuitive for a filter system I am devising. What I would like to know is how to remove just the single key value pair and leave the other keys pairs intact.
Here is my helper function
//Accept a param array which passthrough through tag type eg category/tag and value
function remove_query_params(array $params = [])
{
//Set to array
$existingParams = [];
$existingParams = request()->query();
foreach($params as $key=>$value){
if (isset($existingParams[$value])) {
unset($existingParams[$value]);
}
}
$query = http_build_query($existingParams);
return url()->current() . '?' . $query;
}
//Need to return: user removes tag from filter in blade, URL recontructs without the passed through tag value
//Before
//http://example.com?tags[]=flowers&tags[]=shrubs&category[]=garden
//After
//http://example.com?tags[]=flowers&category[]=garden
This does not work, if I change $value to $key then it will will, but it will remove all keys of the same type, not the behaviour I would like.
I activate this behaviour via a call in the blade template, this forms a href
//Pass through parameter type and parameter value
{{remove_query_params(['category' => $category->id]) }}
Has anybody got any pointers as to where I go next?#
Thanks and fingers crossed I am not far off :)
Adam
I hope this solution will help you:
<?php
function remove_query_params(array $params = [])
{
//Set to array
$existingParams = [
'tags' => [
'aaaa',
'bbbb'
],
'category' => 'ccc'
];
// go trough all parameters
foreach ($existingParams as $key1 => $value1) {
// go to the parameters, which need to be deleted
foreach ($params as $key2 => $value2) {
// only if the keys equals, do something
if ($key1 === $key2) {
// if the param is an array
if (is_array($value1)) {
foreach ($value1 as $k => $v) {
// if the elements to delete are an array
if (is_array($value2)) {
foreach ($value2 as $b => $r) {
if ($v == $r) {
unset($existingParams[$key1][$k]);
}
}
} else {
if ($v == $value2) {
unset($existingParams[$key1][$k]);
}
}
}
} else {
if (isset($existingParams[$key2])) {
unset($existingParams[$key2]);
}
}
}
}
}
$query = http_build_query($existingParams);
return $query;
}
echo remove_query_params(['tags' => 'aaaa']);
echo "\n";
echo remove_query_params(['tags' => ['aaaa', 'bbbb']]);
echo "\n";
echo remove_query_params(['category' => 'ccc']);
echo "\n";
tags is not an associated array. It is just a list of strings. Also, look at the value of $existingParams = request()->query(); It is not the tags array. It is an object that contains it. That is why when you use $key it works but deletes everything because $key is tags. So, in your check $existingParams['tags'] should be checked for the shrubs value. in_array is what you are looking in this case.
Hope this will solve your problem.I just provided the core function to get the things done in a way
$query = "tags[]=flowers&tags[]=shrubs&category[]=garden";
echo (remove_query_params( [ 'tags' => 'shrubs' ], $query ));
function remove_query_params(array $params = [], $query )
{
parse_str( $query, $existingParams );
$existing_keys = array_keys( $existingParams);
foreach($params as $key=>$value){
if( in_array( $key, $existing_keys ) ){
foreach ($existingParams[$key] as $param_key => $param_value) {
if( $param_value == $value ){
unset( $existingParams[$key][$param_key] );
}
}
}
}
$query = http_build_query($existingParams);
return $query;
}

Getting multiple fields from database to an array

I wrote an api call in my Symfony project that returns all fields from my entity with the query defined below..
Now, I need to define just three fields like 'id', 'name', 'value' and to pull values from that fields that are currently stored in a database.
public function getChartData() {
$myResults = $this->getMyRepository()
->createQueryBuilder('s')
->groupBy('s.totalCollected')
->orderBy('s.id', 'ASC')
->getQuery()
->getArrayResult();
$result = array("data" => array());
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
}
The problem is it return just totalCollected field.
One of errors are Call to a member function getId() on array and so on, and I can't figure out a way to pull data from db...
I cannot see in your code where $schoolResult come from but lets guess it string key of some sort.
Notice you trying to set 3 value on the same key so only the last one remains.
Look at:
$a = array();
$a["key"] = 4;
$a["key"] = 6;
It is simple to see that $a["key"] will contains 6 and not 4 or both.
When you do:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
You override the data in $result['data'][$schoolResult] therefor only try totalCollected is there as the last one to set.
In order to fix that you can use:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult]["id] = $label["id"];
$result['data'][$schoolResult]["name"] = $label["name"];
$result['data'][$schoolResult]["totalCollected"] = $label["totalCollected"];
}
Hope that helps!

Database information into separate arrays

here is what I'm trying to do. I'm retrieving information from a database via array. What is happening is the information from the previous array is going into the next array.
Here is the code:
$i = 0;
foreach ($array_name as $key => test_name) {
$id = $test_name['id']
foreach ($test_name['id] as $key => $test_id {
$data = ModelClass::Information($test_id);
$array_name[$i]['new_infroamtion'] = $data'
}
}
So right now based on the code data from the table is correctly going into the first array, however, information based from the first array is going into the second array..
Let me know if you need anymore information.
Thank you
You are using $array_name while you are iterating through $array_name. This is valid code if you want to do this, but I don't think you do. You need to change the second $array_name to something else.
$i = 0;
foreach (**$array_name** as $key => test_name) {
$id = $test_name['id']
foreach ($test_name['id'] as $key => $test_id {
$data = ModelClass::Information($test_id);
**$array_name**[$i]['new_infroamtion'] = $data
}
}
I did find a solution. What I had to do was add the following
$s = array()
Then in the for loop, I added the following code:
foreach ($test_name['id] as $key => $test_id {
$data = ModelClass::Information($test_id);
$s[] = $data
$array_name[$i]['new_infroamtion'] = $s'
}

SimpleXML expecting array error PHP

ok below is my code
<?php
// Last 10 Jobs
function last10IT(){
$xml = simplexml_load_file('http://www.cv-library.co.uk/cgi-bin/feed.xml?affid=101899');
$new_array = array();
//$limit = 5;
//$c = 0;
foreach ($xml->jobs->job as $job) {
// if ($limit == $c) {
// break;
// }
$jobref = $job->jobref;
$title = $job->title;
$date = $job->date;
$new_array[$jobref.$date] = array(
'jobref' => $jobref,
'date' => $date,
'title' => $title,
'salary' => $job->salary,
'location' => $job->location,
);
}
}
ksort($new_array);
$showl = 10;
$n = 0;
foreach ($new_array as $date => $listing) {
print $listing['title'] . PHP_EOL;
}
?>
All I want it to do is filter by category & display a max of 10 results
for example
IT
so is there a way I can pass the category value into the function that I want it to filter by
instead of having to replicate for each category
All I get is :
Warning: ksort() expects parameter 1 to be array, null given in
C:\wamp\www\RECRUITMENTFAIR\functions.php on line 28
Please help guys
It something SO simple causing this error but its driving me mad because I just cannot see it
it is relative simple: you try to use the variable $new_array out of scope:
it is defined within your last10IT() function, but the function ends after the first foreach.
you should either return the array and call the function to get the array or move the part with the ksort and the printing into the function, depending on your needs.
Also was having issues by not having the PHP Extension xmlrpc enabled !
what a tool !
Thats why i was getting failed to open half the time

Push associated variables into array in PHP

I have a loop and each time the loop runs I need to add two variables to an array. What I am trying right now is:
$attach_array['outline'] = array();
foreach ($_POST['attachment'] as $key => $value) {
$attachmentName = $value['name'];
$path = "1";
$name = "alsdkjf";
$attach_array['outline']['path']=$path;
$attach_array['outline']['name']=$name;
}
Then later in the script I try to get these values out for PHPMAILER:
foreach ($attach_array['outline'] as $key => $value) {
$mail->AddAttachment($value['path'], $value['name']);
}
This and other attempts are not working so I'm hoping for some help on putting $name and $path into an array in my first loop to use later.
You are overriding the same variables on each loop. You should do something like this:
$attach_array['outline'][] = array('path' => $path, 'name' => $name);
By doing this, now all the path and values will remain on the array as separate items. You dont have to change the code you are using it from.

Categories