Laravel 5 form another array from database result - arrays

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.

Related

How to structure a multi array to process and sort WooCommerce Order Item data?

How can I extract details from an order into an array, while on the "Order Edit" page and then loop through them?
My array structure isn't correct as can't handle a 3rd item-detail. So each order item somehow needs to be placed into its own sub-array.
Then I want to be able to sort them on item-name and print them out with an echo.
How to achieve the correct array structure to input them and extract?
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'additional_admin_order_data_block_after_shipping_address', 100 );
function additional_admin_order_data_block_after_shipping_address(){
echo '</div><div class="order_data_column order_packing_column">
<h3>' . esc_html__( 'Packing Items', 'woocommerce' ) . '</h3>';
// here goes your code and content
//custom array to list products:
$products_array = array();
$product_tally = 0;
global $post; // <=== Alway at the beginning
// Get an instance of the WC_Order Object
$order = wc_get_order( $post->ID );
// let's decide what order item types we would like to get
$types = array( 'line_item');
// defaults to line_item which allows to get products from order
foreach( $order->get_items( $types ) as $item_id => $item ) {
// order ID
$item_order_id = $item->get_order_id();
// product only and no bundle 'summary' item
if( empty( $item['woosb_ids']) && $item->is_type( 'line_item' ) ) {
// order item name (product title, name of a shipping method or coupon code)
$item_name = $item->get_name();
if ( array_key_exists($item_name, $products_array)) {
$products_array[$item_name] += $item['qty'];
} else {
$products_array[$item_name] = $item['qty'];
}
$product_tally = $product_tally + $item->get_quantity();
}
}
arsort($products_array);
echo '<div class="woocommerce_order_items" id="packing-table">
<div class="thead">
<div class="tr">
<div class="item sortable">Product</div>
<div class="quantity sortable">Qty</div>
</div>
</div>
<div class="tbody" id="order_line_items">';
//display list:
foreach ($products_array as $title => $quantity) {
echo '<div class="lineitem">
<div class="item">';
echo $title.'</div>
<div class="quantity">'.$quantity.'</div>
</div>';
}
echo '<div class="lineitem tally">
<div class="item">Tally of Items</div>
<div class="quantity">'.$product_tally.'</div>
</div>';
echo '</div>
</div>';
}

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

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.

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>

Drupal 7 get images from content type

in my static html site i have:
<li><a href="img/img2.jpg" rel="gallery"
class="pirobox_gall" title=""><img src="img/img2.jpg" alt=""/>
</a></li>
How in Drupal 7 I can get links to images from content type named Galery with fields: title and field_img(IMAGE). Need PHP code...
for example (its not working):
<?php
$mycontent = getcontentby_name('Galery');
foreach ($mycontent as $pic)
{
$link_to_pic = $pic['field_img']['link'];
print $link_to_pic;
}
>
Load the node in which you have your image/images by node_load($node_id), in this object you will have almost all the information related to that particular node.
<?php
$result = db_query('SELECT n.nid FROM {node} n WHERE n.type = :ntype', array(':ntype' => 'galery'));
foreach ($result as $record) {
$node = node_load($record->nid);
print '<img src="';
print file_create_url($node->field_img['und'][0]['uri']);
print '" alt=""/>';
print file_create_url($node->field_img['und'][0]['uri']);
}
?>
this code if 1 record of 'galery' - 1 image.

how to correct find("id = $view")); in cakephp?

I'm learning cakephp from here codes are from the older version of cake so some of the code needs to be updated I have controller which pass data to a view or a layout here is the controller:
BlogController.php
<?php
class BlogController extends AppController {
var $name = 'Blog';
var $uses = array('Blog');
// Used when indexing the page (http://yourdomain.com/blog/)
function index($view = null) {
// What to do if a view is set
if (isset($view))
{
//problem is here
$this->set('article', $this->Blog->find("id = $view"));
$this->render('article');
}
else
{
$this->set('articles', $this->Blog->find('all'));
}
}
}
?>
the problem is this line $this->set('article', $this->Blog->find("id = $view"));
if I replace the line with $this->set('article', $this->Blog->find('first')) it will show me the first item always and nothing will go wrong how can I correct this line so that I can use id?
the layout is article.ctp as follow
<div id="article">
<h1><?= $article['Blog']['title'] ?></h1>
<p class="date"><?= $article['Blog']['date'] ?></p>
<p class="intro"><?= $article['Blog']['introtext'] ?></p>
<p class="main"><?= $article['Blog']['maintext'] ?></p>
</div>
here is the error that I will get by clicking one of items:
Notice (8): Undefined index: id = 2 [CORE\Cake\Model\Model.php, line 2666]
You probably want this:
$this->set('article', $this->Blog->find('first', array('conditions' => array('Blog.id' => $view))));
See: Retrieving Your Data - CakePHP Manual

Resources