Call to a member function save() on null: PROBLEM IN UPDATING - arrays

I cannot update my record using foreach
ScoreController.php
public function updateScore(Request $request, $id)
{
foreach ($request->score as $key => $id) {
$scores = Score::find($request->score[$key]);
$scores->save();
}
//dd($request->all());
return redirect('/tabulation')->with('status', 'Score added!');
}
Blade
#foreach ($scores as $score)
<label for="{{$score->id}}" value="{{$score->id}}"></label>
<input type="text" name="score[]" value="{{$score->score}}"/>
#endforeach

First of all, <label> elements do not have a value attribute:
<label for="{{ $score->id }}" value="{{ $score->id }}"></label>
That value="{{ $score->id }}" does nothing, and isn't sent to the server. If you want to send the score's ID to the server, pass that in your input:
#foreach($scores AS $score)
<input type="text" name="scores[{{ $score->id }}]" value="{{ $score->score }}"/>
#endforeach
Next, in your controller, access your variables correctly:
foreach($request->input("scores") AS $id => $scoreValue){
$score = Score::find($id);
$score->score = $scoreValue;
$score->save();
}
The reason you're getting Call to a member function save() on null is that you're trying to find a Score that has an id of whatever $score->score contains. You're not passing or referencing the id correctly.

Related

How To Insert (array values) More then 1 Value From Input Into 1 Row Of Database In Laravel?

I have a form like bellow with more then 1 Input in my form with 1 name like bellow:
<form>
<input type="text" name="family">
<input type="text" name="inputCurrName[]">
<input type="text" name="inputCurrName[]">
<input type="text" name="inputCurrName[]">
<input type="submit" name="submit" value="submit">
</form>
and i have a table with 2 column with column name Family and CurrName
I want to save multiple names into one Row of CurrName Column in form submission , for example this is my data when submitted:
Family Input: ali
inputCurrName[] Inputs : array(jack,peter,lara)
I want to save only 1 record in database with that data like:
familyColumn Value: ali | CurrNameColumn Value: {jack,peter,lara}
I have used code below but it save 3 record in database!
$input = $request->all();
for ($i = 0; $i <= count($input['inputCurrName']); $i++) {
$user_data = [
'family' => $input['family'],
'curr_name' => $input['inputCurrName'][$i],
];
User::Creat($user_data);
}
What should i DO?
You are doing a for loop checking the length of inputCurrName, so it loops through each inputCurrName, which is why you are getting 3 records per FamilyName. In this case, you would only care about 1 record per FamilyName.
There are a few ways you can insert the array of inputCurrName values into 1 record with FamilyName.
You can use serialize() to create a storable representation of a value and unserialize() to decode it when retrieving from the database.
-OR-
You can use implode() to create a comma delimited list when inserting the record. And upon retrieval from the database, use explode() to iterate through each of the comma delimited values.
-OR-
If you prefer json you can do the same with json_encode() and json_decode() the same way as serialize() and unserialize()
+------------+---------------------------------------------------------+
| FamilyName | CurrName |
+------------+---------------------------------------------------------+
| Ali | a:3:{i:0;s:5:"Laura";i:1;s:6:"Peter ";i:2;s:4:"Jack";} |
| Ali | Laura,Peter,Jack |
+------------+---------------------------------------------------------+
Using the following code will give you an example for the table above. curr_name_optional is part of the $user_data array to showcase implode().
<?php
if(isset($_POST) && count($_POST) > 0) {
$inputFamilyName = $_POST['family'];
$inputCurrentName = $_POST['inputCurrName'];
// Your laravel code here..
$user_data = [
'family' => $inputFamilyName,
'curr_name' => serialize($inputCurrentName),
'curr_name_optional' => implode(',', $inputCurrentName),
'curr_name_optional_1' => json_encode($inputCurrentName)
];
echo "<pre>";
print_r($user_data);
echo "</pre>";
}
?>
<form method="post">
Family Name: <input type="text" name="family"/> <br/>
Curr Name: <input type="text" name="inputCurrName[]"/><br/>
Curr Name: <input type="text" name="inputCurrName[]"/><br/>
Curr Name: <input type="text" name="inputCurrName[]"/><br/>
<input type="submit" name="submit" value="submit"/>
</form>
Also, I would make sure to trim and sanitize your form input data before inserting into the database.
You can simply use a foreach and then convert the data into json format then insert into a single row
$arr = [];
foreach($request->get('inputCurrName') as $key => $value){
$arr[$key] => $value;
}
$user_data = [
'family' => $request->get('family_name'),
'curr_name' => json_encode($arr),
];
User::Create($user_data);
Not sure how its working but, you seem to forgot passing csrf-token in your form. Add #csrf just below the <form> tag.

Codeigniter Model: How to use values from a query for further calculations?

i have a function in a model with the following query, and i want to make some calculations with value1, value2 and value3 outside the query. how to get the values out of this result()?
function ($id,$username$) {
$this->db->select("id,value1,value2,value3,value4");
$this->db->from("table1");
$this->db->where("username=$username and id = $id");
$query=$this->get();
$result = $query->result();
$result['$testvalue'] = (value1 * value2/113) + value3;
return $result; }
can someone help? i already found out how to use values from a table, but not from a query!
ok now i know how to use row_array.
i call the row_array in the controller
$data = $this->model_testmodel->testfunction($id, $username);
...
$this->load->view('pages/view_test', $data);
now i wanna know how the view would look like.
i tried many different ways.
in the moment i am stuck with ...
<?php foreach $data as $value: ?>
<label>Value1:</label>
<input type="text" name="value1" value="<?php echo $value['value1']; ?>">
<label>Value2:</label>
<input type="text" name="value2" value="<?php echo $value['value2']; ?>">
...
<?php endforeach; ?>
but i get two errors:
Message: Undefined variable: data
Message: Invalid argument supplied for foreach()
Try this...
function ($id,$username)
{
$this->db->select("id,value1,value2,value3,value4");
$this->db->from("table1");
$this->db->where(array('id'=>$id,'username'=>$username));
$query=$this->db->get();
$result = $query->row();
$testvalue = (($result->value1 * $result->value2/113) + $result->value3);
//test here
echo $testvalue;
$res = array();
$res['testvalue'] = $testvalue;
$res['value1'] = $result->value1;
$res['value2'] = $result->value2;
$res['value3'] = $result->value3;
return $res;
}
It returns $res as array.Easy to execute of you got problem comment.. if it works accept.Lets enjoy..
Then make a function call and accept array in a variable..like this..
first load model then make function call.from your controller
$this->load->model('model_name');
$data= $this->model_name->function_name($id,$username);
//Fetch returned array like this..
echo $data['testvalue'];
echo $data['value1'];
//so on

Laravel 5 form another array from database result

I'm new to Laravel and I've been struggling too long with this now, tried to search SO and google for information but can't solve this.
I'm creating blog and need to make some kind of navigation/archive which displays year and months and how many blog posts there have been per year and invidual month. By clicking those years/months I would then display posts during that time period on different view.
I want them to be displayed in the view like this:
2015 (10)
January(3)
February(3)
March(3)
April(1)
2014 (2)
May(1)
June(1)
And so on.
I got database query like this:
$links = \DB::table('posts')
->select(\DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) id'))
->where('active',1)
->groupBy('year')
->groupBy('month')
->orderBy('year', 'desc')
->orderBy('month', 'desc')
->get();
Which gives me table like this:
array:3 [
0 => {#275
+"year": "2015"
+"month": "10"
+"month_name": "October"
+"id": "3"
}
1 => {#274
+"year": "2015"
+"month": "9"
+"month_name": "September"
+"id": "1"
}
2 => {#273
+"year": "2014"
+"month": "8"
+"month_name": "August"
+"id": "1"
}
]
How can I print it on my view like I described?
If I go through the array in views like this:
#foreach($links as $link)
<h3 class="text-uppercase">{{ $link->year }}</h3>
<p><small class="blog_date">{{ $link->month_name }} ({{ $link->id }}) </small>
#endforeach
I tried to use foreach-loop in my Controller to create another array from DB-results where structure would be in correct form and I could just use foreach to print it on the view, but couldn't get it work.
I know I'm near the solution, but I'm still learning. Please someone tell me which is the best way to do this.
Try this in your blade:
<?php $first_loop = 0; ?>
#foreach($links as $link)
#if($first_loop == 0)
<?php
$first_loop = 1;
$current_year = $link->year;
?>
<h3 class="text-uppercase">{{ $link->year }}</h3>
<p><small class="blog_date">{{ $link->month_name }} ({{ $link->id }}) </small></p>
#else
#if($current_year == $link->year)
<p><small class="blog_date">{{ $link->month_name }} ({{ $link->id }}) </small></p>
<?php
$current_year = $link->year;
?>
#else
<h3 class="text-uppercase">{{ $link->year }}</h3>
<p><small class="blog_date">{{ $link->month_name }} ({{ $link->id }}) </small></p>
<?php
$current_year = $link->year;
?>
#endif
#endif
#endforeach
You can do some preparation on your data before outputting it. For example:
$links = // .. your query;
$years = array_pluck($links, 'year');
$results = [];
foreach($years as $year)
{
$posts_count = 0;
$posts = array_where($links, function($key, $value) use ($year, $posts_count){
if($value['year'] == $year)
{
$posts_count += $value['id'];
return true;
}
return false;
});
$results[$year] = ['posts' => $posts, 'posts_count' => $posts_count];
}
You can do the above in some repository/service class, or even in the controller if you want (although not recommended)
And then in your view you can have something like:
#foreach($results as $year => $result)
{{ $year }} {{ data_get($result, 'posts_count') }}
<ul>
#foreach(data_get($result, 'posts') as $monthly_post)
<li>{{ data_get($monthly_post, 'month_name') }} {{ data_get($monthly_post, 'id') }}</li>
#endforeach
</ul>
#endforeach
This code is untested, so use it as inspiration for your approach, not a copy-paste solution.

CodeIgniter Dropdown menu fetching data from database column

I am having a problem. Please let me know if there is a solution. I am new to codeigniter therefore, sorry in advance if there is a silly one!
I am trying to fetch data from a database. Table name is fw_main_cat which have fields (cat_id, cat_parent_id, cat_level, cat_title, cat_menu_order and cat_status). cat_id is unique.
I want a dropdown menu (in view) to take all the data of a column cat_title through cat_level (which are int). So, how can I do?
Here is my code which I have tried so far.
This is Model :
public function cat_level_one($cat_level)
{
$sql = "Select * from fw_main_cat Where cat_level=? ";
$result = $this->db->query($sql, $cat_level);
if($result->num_rows() > 0)
{
return $result->result_array();
}
else { return false;
}
}
This is Controller :
public function getcategory()
{
if ($this->session->userdata('session_status'))
{
$cat_level_one = $this->admin_cat_model->cat_level_one($cat_level);
$data['cat_level_one'] = $this->admin_cat_model->cat_level_one($cat_level);
$this->session->set_userdata('cat_level', $_POST['cat_level']);
$this->laod_view('admin_view/admin_cat/view_add_category', $data);
}else {
redirect ('admin_view/admin_cat/view_category');
}
}
This is View (dropdown menu):
<li class="full-row">
<select name = 'cat_level_one' id = 'cat_level_one'>
<option value="<?php if(isset ($cat_level_one) && $cat_level_one != ''){ foreach ($cat_level_one as $cat_one){ echo $cat_one->cat_id; } } ?>"
selected="selected">------------Select Category------------</option>
Thanks! for the consideration.
Updated code -
// in model
function cat_level_one($cat_level)
{
$this->db->where('cat_level',$cat_level);
$q = $this->db->get('fw_main_cat');
$data = $q->result_array();
return $data;
}
//controller function
public function getcategory()
{
**if ($this->session->userdata('session_status'))
{
$data['cat_level_one'] = $this->admin_cat_model->cat_level_one($cat_level);**
//Where this post data comes from??
$this->session->set_userdata('cat_level', $_POST['cat_level']);
$this->laod_view('admin_view/admin_cat/view_add_category', $data);
}else {
redirect ('admin_view/admin_cat/view_category');
}
}
//in view
<li class="full-row">
<select name = 'cat_level_one' id = 'cat_level_one'>
<option value="">-- Select Category --</option>
<?php foreach($cat_level_one as $cat_one){ ?>
<option value="<?php echo $cat_one->cat_id; ?>"><?php echo $cat_one->cat_title; ?></option>
<?php } ?>
</select>
</li>

Zend_Form array notation with no indices

I would like to create a form that allows the user to input any number of values, each in a separate text field using an array notation. The example expected HTML output is:
<dd id="dupa-element">
<input type="text" name="dupa[]" value="">
<input type="text" name="dupa[]" value="">
</dd>
However, I can't seem to find a way to introduce multiple input elements within a single element, using array notation without indices.
Currently, I do this:
$elt1 = new Zend_Form_Element_Text('1');
$elt1->setOptions(array('belongsTo' => 'dupa'));
$elt2 = new Zend_Form_Element_Textarea('2');
$elt2->setOptions(array('belongsTo' => 'dupa'));
While this works, Zend_Form treats these as independent elements (which can have different sets of validators and filters - that's sort of cool) and the resulting HTML is something along these lines:
<dd id="dupa-1-element">
<input type="text" name="dupa[1]" id="dupa-1" value="">
</dd>
<dd id="dupa-2-element">
<input type="text" name="dupa[2]" id="dupa-2" value="">
</dd>
Is there a (preferably simple) way to achieve the indexless array notation I'm after?
I would follow MWOP's tutorial on creating composite elements. More work, but it's less Trial&Error then akond's solution. Basic idea for me would be extending the Zend_Form_Element_Multi (what you want is how Zend_Form_Element_Multiselect/MultiCheckbox works).
I managed to do this by having a "container subform", and then adding subforms to that "container" e.g.:
$container = new Zend_Form_SubForm();
$subform1 = new Zend_Form_SubForm();
$container->addSubForm($subform1, '1');
$subform2 = new Zend_Form_SubForm();
$subform2->addSubForm($subform1, '2');
$mainForm = new Zend_Form();
$mainForm->addSubform($container,'mysubforms');
Hope that helps.
You need a custom view helper for that.
class Zend_View_Helper_FormMySelect extends Zend_View_Helper_Abstract
{
function formMySelect ($name, $value = null, $attribs = null, $options = null, $listsep = "<br />\n")
{
$result = array ();
foreach ($options as $option)
{
$result [] = sprintf ('<input type="text" name="%s[]" value="">', $name);
}
return join ($listsep, $result);
}
}
Than have in your form something like that:
$form = new Zend_Form();
$form->addElement ('select', 'test', array (
'label' => 'Test',
'multioptions' => array (
'test 1',
'test 2',
'test 3',
),
));
$form->test->helper = 'formMySelect';

Resources