how to fetch data from table if data in inserted in object form in laravel 8 - laravel-8

#foreach ($all_products as $product)
#foreach(json_decode($product->attributes) as $attributes)
#if($attributes[1]->name==$color)
<x-frontend.product.product-card :product="$product" />
#endif
#endforeach
#endforeach
data fetch only this {"1":[{"type":"color","name":"blue"}]}
and i have to find {"2":[{"type":"size","name":"m"}]

Related

Start Order by data from table that is found in another table

My question may be not easy to explain but I am going to do my best.
I have 3 tables :
medicine
patient
patient_medicine
the third table contains 3 columns :
auto increment (id)
medicine_id
patient_id
I make a query that display all data in medicine table and if there is a patient id found in patient_medicine table I check it and those that are not found are not checked.
A- controller
public function showPatientMedicine()
{
$data['patient_id']=$this->input->post('patient_id');
$data['medicine'] = $this->model_admin->medicine();
$this->load->view('admin/show-Patient-Medicine',$data);
}
B- VIEW
<table>
<thead>
<tr>
<th>List</th><th></th>
</tr>
</thead>
<tbody>
<?php
foreach($medicine as $row){
$patient_med=$this->db->select('medicine_id')
->where('patient_id',$patient_id)
->where('medicine_id',$row->id)
->get('patient_medicine')->row('medicine_id');
if($row->id==$patient_med){
$checked="checked";
} else {
$checked="";
}
?>
<tr>
<td>
</td>
<td>
<input type='checkbox' value="<?=$row->id?>" <?=$checked?> />
</td>
</tr>
<?php
}
?>
</tbody>
</table>
THIS QUERY SHOWS ME ALL MEDICINES AND CHECK THE MEDICINES THAT ARE FOUND IN PATIENT_MEDICINE TABLE
MY QUESTION IS :
HOW CAN I SHOW ALL MEDICINES THAT ARE CHECKED IN THE FIRST POSITION OR HOW TO ORDER BY CHECKED CHECKBOX ?
THANK YOU IN ADVANCE.
Try this,
SELECT * FROM `medicine` as a left join (select medicine_id,patient_id from patient_medicine where patient_id = 2) as b on a.id = b.medicine_id
Put the above query in your controller, it will automatically sort the result based on patient id, if patient details found. it will return null for all other details in rows except medicine details.
So you can just
<?php foreach($medicine as $row){ ?>
<input type='checkbox' value="<?=$row->id?>" <?php echo !is_null($row->patient_id)?'checked':''; ?> />
<?php } ?>

Laravel Display a record details while grouped by year or month

I just moved to the laravel framework and am starting to migrate some legacy sites and I have hit a problem with SQL or blade - dunno which.
I have to display a load of rows 'sports classes' which are grouped by year and then month. each needs to show attendance etc.
I am unsure which way to proceed.
I am able to display all rows and sort by date - easy squeezy
I am able to groupBy year AND month - fiddly but sorted it.
These are all displayed in an accordian.
Click the month - the individual rows drop down - you get the idea
I can get a number of rows per month/year
What I am unable to figure out is how to actually display the rows.
The groupBy is this:
$LinkClasses = DB::table('classes_lists')
->select('id, class, teacher, size')
->select(DB::raw('YEAR(date) AS year, MONTH(date) AS month, MONTHNAME(date) AS month_name, COUNT(*) post_count'))
->groupBy('year')
->groupBy('month')
->orderBy('year', 'desc')
->orderBy('month', 'desc')
->orderBy('id', 'desc')
If the code you provided is within your controller, then you can append ->get() after your last ->orderBy(). This will return a Collection. You can then do whatever you want with the Collection (http://laravel.com/api/master/Illuminate/Support/Collection.html), including conversion to an array using ->toArray(), but I think it would be best to utilize the Eloquent ORM if possible.
Anyway, once you have it in the format you want, just pass it to the view like so:
return view('your.view', compact('LinkClasses'));
Then, inside the your.view blade template, you can access this by using the following:
#foreach ($LinkClasses as $currentRow)
<tr>
<td>{{ $currentRow['id'] }}</td>
<td>{{ $currentRow['class'] }}</td>
<td> ... </td>
</tr>
#endforeach
Best guess I can offer without seeing the blade template to get a better idea of what you're doing. Hope that helps!
UPDATE BASED ON OP FEEDBACK:
Since you are only receiving a single record, it seems as though the issue lies in your query. I suggest you simplify your query to fetch all records and then do your sorting within an array. Something like this in your controller:
$allClasses = DB::table('classes_lists')->all();
foreach ($allClasses as $currentClass) {
$yearMonth = date('Y-m', $currentClass['date']);
$classesByYearMonth[$yearMonth][] = $currentClass;
}
ksort($classesByYearMonth);
/* now you have an array of all classes sorted by year-month like this:
// $classesByYearMonth[2014-01] = array(
// [0] => array(1, 'class name', 'teacher name', 23),
// [1] => array(2, 'another class', 'different teacher', 25),
// ...
// );
//
// $classesByYearMonth[2014-02] = ...
*/
return view('your.view', compact('classesByYearMonth'));
Then, inside your blade template:
#foreach ($classesByYearMonth as $yearMonth => $classListArray)
Found {{ sizeof($classListArray) }} classes for {{ $yearMonth }}
#foreach ($classListArray as $currentClass)
<div>
<div>ID: {{ $currentClass['id'] }}</div>
<div>Class: {{ $currentClass['class'] }}</div>
<div>Teacher: {{ $currentClass['teacher'] }}</div>
<div>Size: {{ $currentClass['size'] }}</div>
</div>
#endforeach
#endforeach
I will leave it to you to fix the formatting to make your accordion work. But hopefully that will get you on the right path.
DNoe - thank you so much.
Your reply put me on exactly the right track.
I had to mod some bits due to laravel ambiguities and add the strtotime but the logic was all there.
foreach ($allClasses as $currentClass) {
$ym = $currentClass['date'];
$yearMonth = date("Y-m",strtotime($ym));
$classesByYearMonth[$yearMonth][] = $currentClass;
}
krsort($classesByYearMonth);
return View::make('classes.index', compact('classesByYearMonth'));
The css is simple from here.
I owe you some beers. And thanks for helping me take my head from my butt!
Send me a pm and i would be very very happy to forward beer donation :o
Great work and thank you again. :)
Also, part of the problem was that the results were throwing an stdObject rather than an array.
Being able to compare your code with my own has enabled me to create a dbquery with multiple joins from which meaningfull data is selected and then converted to an array.
$classes = DB::table('table2')
->join('table1', 'table2.id', '=', 'table1.id2' )
->join('table3', 'table1.id3', '=', 'table3.id' )
->orderBy('classes_lists.date','DESC')
->get(array('table1.id', 'teacher', 'date', 'size', 'students', 'fname', 'classname', 'table1.notes'));
$cfr = count($classes);
foreach($classes as $object)
{
$arrays[] = (array) $object;
}
foreach ($arrays as $currentClass){
$ym = $currentClass['date'];
$yearMonth = date("Y-m",strtotime($ym));
$clazByYearMonth[$yearMonth][] = $currentClass;
}
krsort($clazByYearMonth);
This was the output into blade:
Not formatted :
#foreach ($clazByYearMonth as $yearMonth => $classListArray)
Found {{ sizeof($classListArray) }} classes for {{ $yearMonth }}
#foreach ($classListArray as $currentClass)
<div>
date: {{ $currentClass['date'] }} | class: {{ $currentClass['classname'] }} | Size: {{ $currentClass['size'] }} Teacher: {{ $currentClass['fname'] }} |
</div>
#endforeach
#endforeach

Deleting single item with submit from database results in two ID's and strings

When I try and delete an entry from the code below it seems to spew out two array values with different index numbers and will not delete the entry. If I click multiple times it finally gets the correct ID but only by some random chance.
Using echo var_dump($deleted) results in something like:
String(2) "10"
String(1) "7"
These can vary and seems to be random.
I have reduced my whole plugin to just the code below thinking that maybe some other submit query might be interfering with it. And still I get two ID's with unknown string assignments.
Any ideas?
function myplugin_update_page(){
global $wpdb;
$update_page_list = $wpdb->get_results('SELECT * FROM wp_update_page');
$active = $wpdb->get_var("SELECT * FROM wp_update_page WHERE active='on'");
echo '<form method="post" action=""><table>';
foreach ( $update_page_list as $update ) { ?>
<tr>
<td><input type="image" src="<?php echo plugin_dir_url(__FILE__).'images/delete.png'; ?>" name="delete[]" value="<?php echo $update->ID; ?>" /></td>
</tr>
</table>
</form>
</div>
<?php
}
if(isset($_POST['delete'])) {
$delete = $_POST['delete'];
foreach ($delete as $deleted) {
$wpdb->query("DELETE FROM wp_update_page WHERE ID = $deleted");
}
echo "<script type='text/javascript'>window.location=document.location.href;</script>";
}
}

Yii Grid, multiple management rows

i have a questions about managament rows in grid. For example we have food/cost table like:
Fruit | cost
------------
Apple | 10$
Bannan| 5$
We can create form like:
<form>
<input type='text' name='Fruits[0][fruit] value='Apple' /> <input type='text' name='Fruits[0][cost] value='10$' /> <br>
<input type='text' name='Fruits[1][fruit] value='Bannan' /> <input type='text' name='Fruits[1][cost] value='5$' />
</form>
And save all it like:
if ($is_new)
if(isset($_POST['Fruits'])) {
foreach ($_POST['Fruits'] as $fruit) {
$model = new Fruit();
$model->attributes = $fruit;
$model->save();
}
}
} else { //here code for update, $model->load()... }
All fine, we can update both rows... But that if i want add new? All fine method above make all good, but what if i delete 1 row? In my base i will have 2 rows, but i need only 1.
Here 2 ways i see:
1. Delete all fruits from databse on every update when POST count != databse count
2. We can load database rows, write loop, check every row... but its so hard, so many code...
How you manage new and deleted rows?
Use Yii data handlers to print results, like 'CGridView' :
http://www.yiiframework.com/doc/api/1.1/CGridView/

Codeigniter inserting value into array

I asked a question on SO a few hours back.
How to insert an Array of field names from a form into SQL database in Codeigniter.
<tr>
<td><input type="text" name="user[0][name]" value=""></td>
<td><input type="text" name="user[0][address]" value=""><br></td>
<td><input type="text" name="user[0][age]" value=""></td>
<td><input type="text" name="user[0][email]" value=""></td>
<tr>
<td><input type="text" name="user[1][name]" value=""></td>
<td><input type="text" name="user[1][address]" value=""><br></td>
<td><input type="text" name="user[1][age]" value=""></td>
<td><input type="text" name="user[1][email]" value=""></td>
</tr>
..........//so on
This is the best answer I got
foreach($_POST['user'] as $user)
{
$this->db->insert('mytable', $user);
}
Now I want to pass a id generated from user session data into this array + a few other values like current time
Is it possible to tweak the above solution?
The Previous Discussion Here
foreach($_POST['user'] as &$user)
{
$user['additional_data'] = $_SESSION['additional_data'];
$user['current_time'] = time();
$this->db->insert('mytable', $user);
}
Note the & in &$user which is a pass by reference which allows manipulation of an array within a foreach loop. If you reference user later remember to unset($user) to remove the reference to the last element of the $_POST['user'] array.
I don't know if I'm missing something here, but can't you just remove the foreach and build your code like this:
$var1 = $_POST['user_var1'] * 3 + 1 / 5;
$this->db->insert('mytable', $var1);
$var2 = gettime();
$this->db->insert('mytable', $var2);
....
(where gettime() should be replace with whatever the PHP command for getting time is, plus maybe a formatting function)