Optimization of Eloquent queries in Laravel 4 - php

I've just recently started using Laravel and I've got a problem, that my page is really slow.
The issue is that my queries are not ideal:
`
<div class="container">
#foreach ($product as $single)
<?php
$tagy = $single->tags()->get();
echo "<div class='item";
foreach($tagy as $tag) {
$premenna = Tags::where('id','=',$tag->tagID)->first();
echo " item".$premenna->id;
}
echo "'>";
?>
<div class="thumbnail porfolio">
<img class="image" src="<?=Croppa::url($single->destinationPath.'/'.$single->coverphoto, 250)?>" />
<div class="caption">
<div class="info">
<h4 style="font-weight: bold;">{{ $single->name }}</h5>
<p style="font-size: 15px; margin-bottom: 0px;">{{ $single->city }}</p>
<p class="date">{{ $single->date }}</p>
</div>
<div class="map-location">
<i class="fa fa-dot-circle-o fa-2x"></i>
</div>
<div class="tagy">
<?php
foreach($tagy as $tag) {
$variable= Tags::where('id','=',$tag->tagID)->orderBy('name')->first();
echo "<a class='hashtag tag".$variable->id."'>".$variable->name." </a>";
}
?>
</div>
</div>
</div>
</div>
#endforeach
</div>`
This is my Controller function:
protected function index()
{
$product = Product::where('active','=',1)->orderBy('date')->get();
$tagy = Tags::orderBy('name')->get();
return View::make('uvod',['product' => $product, 'tags' => $tagy]);
}
I've made one-to-many relationship between Product Class and ProductTag Class - that's the fucntion tags();
Could you please somehow help me optimizing the code (queries)? I would like to use #foreach function only once if possible - when i deleted the foreach functions inside the main one the page speed significantly improved.
Thank you very much for any kind of help :)

Related

Undefined variable $p and foreach() argument must be of type array|object, null given in codeigniter 3

I am trying to pass an array that gets initialised when it gets queried from the database.
The array of products that I try to pass and display in the view just throws an error and i cannot figure out why.
I am using codeigniter 3.
ProductsModel.php
function get_all_products()
{
$this->db->select("produceCode,description,category,supplier, quantityInStock, bulkSalePrice,photo");
$this->db->from('products');
$query = $this->db->get();
return $query->result();
}
ProductsController.php
public function listProducts()
{
$data['p']=$this->ProductsModel->get_all_products(/*2, $this->uri->segment(3)*/);
$this->load->view('products',$data);
}
products.php
<?php foreach( $p as $row) { ?> // line of code thats causing the error
<div class="col-md-3">
<div class="card p-3">
<div class="text-center"> <!--<img src="../assets/images/products/thumbs/--><?php /*$row->photo;*/?>" width="200"> </div>
<div class="product-details"> <span class="font-weight-bold d-block">$ 7.00</span> <span><?php echo 'hi'/*$row->description;*/?></span>
<div class="buttons d-flex flex-row">
<div class="cart"><i class="fa fa-shopping-cart"></i></div> <button class="btn btn-success cart-button btn-block"><span class="dot">1</span>Add to cart </button>
</div>
</div>
</div>
</div>
<?php } ?>
any suggestions would be great
You are returning a variable named $data in your controller, but in your view you are looping through $p.
Try this:
foreach ($data['p'] as $row)

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$created_at

I'm having an issue that possibly a lot of people already had on here, but I can't seem to figure it out.
I'm trying to use Carbon and Paginate in the same variable, but keep getting the error shown in the title.
The code that I'm trying to use it with is:
Controller:
public function index()
{
$announcements = Announcement::withCount('replies')->orderBy('created_at', 'desc')->paginate(5);
$birthdays = User::whereRaw('DAYOFYEAR(curdate()) <= DAYOFYEAR(birthday) AND DAYOFYEAR(curdate()) + 365 >= dayofyear(birthday)')
->orderByRaw('DAYOFYEAR(birthday)')
->get();
$date = Carbon::create($announcements->created_at)->locale('nl');
return view('home', compact('announcements', 'birthdays', 'date'));
}
View:
#foreach($announcements as $announcement)
<div class="announcement">
<div class="row">
<div class="col-lg-11">
<h2 style="font-size:1.5rem;" class="text-capitalize">{{$announcement->post_title}}</h2>
#if($announcement->post_image == null)
#else
<img src="{{$announcement->post_image}}" style="width:100%;">
#endif
<p style="font-size: 0.8rem;">{{$birthday->isoFormat('LL')}} | Geplaatst door <span>{{$announcement->username}}</span> | <span style="color:#007ac3">{{$announcement->replies_count}} reacties</span></p>
<p style="margin-top: -10px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden;">{!! Str::words($announcement->post_content, 20) !!}</p>
</div>
<div class="col-lg-1">
#if(Auth::user()->admin == 1)
<i class="fal fa-dumpster" style="text-align: center;position: relative;font-size: 20px;"></i>
#endif
</div>
</div>
<p>Meer lezen <i class="fas fa-angle-double-right"></i></p>
<hr>
</div>
#endforeach
I'm expecting it to translate the date to Dutch, but for now all I'm getting is the error.
The ->paginate() method returns a LengthAwarePaginator object, not a single model. You'll need to map the date function over each element in the Collection object.

view can't find variable (laravel)

I have the following action in my controller:
public function viewPost($id)
{
$current_post = forum_post::with('replies')->where('id', $id)->get();
return view('forumViewPost',['currentPost', $current_post]);
}
Then I have the following view:
#extends('layout.app')
#section('content')
<div class="container">
<div class="nk-gap-2"></div>
<ul class="nk-forum nk-forum-topic">
<li>
<div class="nk-forum-topic-author">
<img src="assets/images/avatar-2-sm.jpg" alt="Kurt Tucker">
<div class="nk-forum-topic-author-name" title="Kurt Tucker">
{{$currentPost->nickname}}
</div>
<div class="nk-forum-topic-author-role">
Member
</div>
</div>
<div class="nk-forum-topic-content">
{{$currentPost->content}}
</div>
<div class="nk-forum-topic-footer">
<span class="nk-forum-topic-date">June 19,
2017</span> <span class="nk-forum-action-btn"> Reply</span>
<span class="nk-forum-action-btn"> Spam</span>
<span class="nk-forum-action-btn"><span class="nk-action-heart liked"><span class="num">1</span>
Like</span></span>
</div>
</li>
#foreach($currentPost->replies as $replies)
#endforeach
</ul>
</div>
#endsection
now when I run this. I get the following error:
Undefined variable: currentPost
Can anyone tell me what I've done wrong?
If you use [] you may write this ['currentPost' => $current_post]
All
public function viewPost($id)
{
$current_post = forum_post::with('replies')->where('id', $id)->get();
return view('forumViewPost',['currentPost' => $current_post]);
}
You can also you compact(''); and as Wreigh mentioned change $current_post to $currectPost
public function viewPost($id)
{
$currentPost = forum_post::with('replies')->where('id', $id)->get();
return view('forumViewPost', compact('currentPost'));
}

model function call in blade view laravel

My model code
how we can call this function in blade.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BasicModel extends Model
{
public static function get_product_count($id){
$query = "select COUNT(sub_id) AS count FROM products WHERE products.sub_id = $id";
print_r($query);
return $query->row_array();
}
}
My view.blade.php code
count in foreach loop or show in all category
#foreach ($r as $row)
<li class="grid-item type-rent">
<div class="property-block">
<img src="{{ URL::to('/template/images/background-images/sub-category-images/' .$row->sub_cat_images. '')}}" alt=""> <!-- <span class="images-count"><i class="fa fa-picture-o"></i> 2</span> <span class="badges">Rent</span> -->
<div class="property-info">
<h4>{{ ucwords(substr($row->sub_cat_name, 0, 22)) }}</h4>
<span class="location">NYC</span>
<div class="price"><strong>Items</strong><span>
<!-- start count code from here -->
$data = $this->BasicModel->count {{ ($row->sub_id) }}
echo $data['count'];
</span></div>
</div>
<!-- <div class="property-amenities clearfix"> <span class="area"><strong>5000</strong>Area</span> <span class="baths"><strong>3</strong>Baths</span> <span class="beds"><strong>3</strong>Beds</span> <span class="parking"><strong>1</strong>Parking</span> </div> -->
</div>
</li>
#endforeach
My BasicController Code
public function grid(Request $request, $id)
{
if ($id == 1) {
$r = DB::table('sub_category')->select('*')->where('cat_id', $id)
->where('sub_status', '1')->orderBy('sub_id', 'asc')->get();
$name = DB::table('category')->where('cat_id', $id)->get();
return view('buy-and-sell/grid', compact('r','name','count'));
}
image for your help
image for your help
problem in this image please solve the problem
Although its no good Practice Accessing the DB in Blade (better do this in the controller and pass the data) you can do:
<div class="price"><strong>Products</strong>
<span>
{{ BasicModel::where('sub_id', $row->sub_id)->count() }}
</span>
</div>
Its not tested, but have a look at the Eloquent docs, the count() method is explained there.
Update: I am not shure if laravel will find the class BasicModel (I never would access Models directly in blade, as stated do this in the controller and pass the data.) So maybe you need to write it with the full Namespace most likely {{ \App\BasicModel::where() }}.

In category counts his item from database table

My model code
how we can call this function in blade.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BasicModel extends Model
{
public static function get_product_count($id){
$query = "select COUNT(sub_id) AS count FROM products WHERE products.sub_id = $id";
print_r($query);
return $query->row_array();
}
}
My view.blade.php code
count in foreach loop or show in all category
#foreach ($r as $row)
<li class="grid-item type-rent">
<div class="property-block">
<img src="{{ URL::to('/template/images/background-images/sub-category-images/' .$row->sub_cat_images. '')}}" alt=""> <!-- <span class="images-count"><i class="fa fa-picture-o"></i> 2</span> <span class="badges">Rent</span> -->
<div class="property-info">
<h4>{{ ucwords(substr($row->sub_cat_name, 0, 22)) }}</h4>
<span class="location">NYC</span>
<div class="price"><strong>Items</strong><span>
<!-- start count code from here -->
$data = $this->BasicModel->count {{ ($row->sub_id) }}
echo $data['count'];
</span></div>
</div>
<!-- <div class="property-amenities clearfix"> <span class="area"><strong>5000</strong>Area</span> <span class="baths"><strong>3</strong>Baths</span> <span class="beds"><strong>3</strong>Beds</span> <span class="parking"><strong>1</strong>Parking</span> </div> -->
</div>
</li>
#endforeach
My BasicController Code
public function grid(Request $request, $id)
{
if ($id == 1) {
$r = DB::table('sub_category')->select('*')->where('cat_id', $id)
->where('sub_status', '1')->orderBy('sub_id', 'asc')->get();
$name = DB::table('category')->where('cat_id', $id)->get();
return view('buy-and-sell/grid', compact('r','name','count'));
}
image for your help
image for your help
problem in this image please solve the problem
I think you are closing the PHP tag in the wrong place. Change to this:
<?php print_r($count);
$data = $this->BasicController->count {{ ($row->sub_id) }}
echo $data['count'];//here is the rightplace to close your PHP ?>
</span></div>
All PHP code needs to stay between the <?php and ?>
Looking to your image, apparently, it's printing the $count and then it's printing the plain text , so you have 80$data = ...
If you counted your rows in controller by the code below
$count = DB::table('products')->where('sub_id', $id)->count();
then why wrote so many code in html for counting?
Remove all code form counting form your html and just use this {{ $count }}

Categories