Count how many reviews a post has - Laravel 5.2 - php

I need to count how many reviews a post has. How would I go about doing that?
Here is my Listing.php Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Listing extends Model
{
public function reviews()
{
return $this->hasMany('\App\Review');
}
}
Here is my Review.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Review extends Model
{
protected $fillable = ['stars','name','comment'];
public function listing()
{
return $this->belongsTo('\App\Listing');
}
}
Here is my method that I'am trying to count in controller
public function mostReviews(Request $request) {
$listings = Review::orderBy('-- most reviews here --')->take(10)->get();
$headline = 'Most Reviewed Listings';
return view('pages.listings', compact('listings', 'headline'));
}
Here is my review table:

I haven't tested it but the query below (using the query builder) should give you what you want - 10 listings with the most reviews. Additionally average_stars column should return average stars rate. You can easily modify the query to get 10 highest rated listings by changing orderBy to average_stars.
$listings = \DB::table('reviews AS r')
->select([
'r.listing_id',
\DB::raw('COUNT(*) AS no_of_reviews'),
\DB::raw('AVG(r.stars) AS average_stars'),
'l.*'])
->join('listings AS l', 'l.id', '=', 'r.listing_id')
->limit(10)
->orderBy('no_of_reviews', 'DESC')
->groupBy('listing_id')
->get();
Please note version up to version 5.2 of Laravel this will return array of stdObject. You can easily access those in your blade template in a similar way as Eloquent Collection.
#foreach($listings as $listing)
<tr>
<td>{{ $listing->id }}</td>
<td>{{ $listing->title }}</td>
<td>{{ $listing->no_of_reviews }}</td>
<td>{{ floor($listing->average_stars) }}</td>
</tr>
#endforeach

This is what I did:
public function mostReviews() {
$reviews = DB::table('reviews')
->select(DB::raw('AVG(stars) as review_score, listing_id'))
->groupBy('listing_id')
->orderBy('review_score', 'desc')
->limit(10)
->get();
foreach($reviews as $key => $review) {
$reviews[$key] = Listing::find($review->listing_id);
}
return view('listings.most-reviews', [
'listings' => $reviews
]);
}

Try this
$review = Review::orderBy('-- most reviews here --');
$reviewCount = $review->count();
$listings=$review->take(10)->get();

The following should work
$listing = Listing::with('reviews')->orderByRaw(function($listing)
{
return $listing->review->count();
}, desc)->take(10)->get();

in your listing model:
public function countReview() {
return count($this->reviews);
}
in your views :
{{$listing->countReview()}}
maybe in controller you can write somthing like :
public function mostReviews() {
Review::orderBy('listing', 'desc')->blahblah; // or 'asc'
}

Related

How to fix "laravel pagination NOT updating on search"

I'm making a table of orders that have a specific current step in this case the step is 'NESTEN' and some other where statements to get the orders back that I need.
Because I don't want a list with more than 400 orders on 1 page I want to use laravels pagination functionality that also give a performance boost on the list of more than 100.000 records. The laravel pagination works as is should but the problem comes when I want to use the filter I made.
I made a dropdown list that needs to filter based on material of the orders that are in the list. In the table I see the filtered orders but the pagination has the same page count and order count as before. So to the point, the problem is that the pagination is not updating after filtering the collection from the query.
What I already tried was some googling and found several solutions that didn't solve my problem or even caused more problems...
Also added a $orders->filter function to remove orders that don't meet up the filter requirements but no result...
To keep it understandable for now I added the code in the Route file.
My route is as followed
Route::get('orders/nesten', function(Request $request) {
$orders = ShopOrder::where([
['ItemCode', 'LIKE', 'CM%'],
['Exact', '=', null],
['Nesting', '=', null],
['IsOnHold', '!=', 1],
['ShopOrderRoutingStepPlanCount', '!=', 0]
])->paginate(50);
$filteredCollection = $orders->filter(function ($order) use($request) {
if($request->exists('material')) {
return $order->getCurrentStep() == 'Nesten'
&& $order->getMaterial() == $request->get('material');
}
return $order->getCurrentStep() == 'Nesten';
});
$orders->setCollection($filteredCollection);
return view('dashboard/actions/Nesten')->with('shopOrders', $orders);
});
In the ShopOrder Model I declared the functions ->getMaterial() and ->getCurrentStep() as
public function routingStepPlans() {
return $this->hasMany('App\Models\Exact\ShopOrder\RoutingStepPlan', 'ShopOrder', 'ID');
}
public function materialPlans() {
return $this->hasMany('App\Models\Exact\ShopOrder\MaterialPlan', 'ShopOrder', 'ID');
}
public function getCurrentStep() {
$current = $this->routingStepPlans()->where('LineNumber', ($this->timeTransactions()->count() + 1))->first();
if(isset($current->Description)) {
return $current->Description;
}
return 'Afgerond';
}
public function getMaterial() {
$material = $this->materialPlans()->where('ItemCode', 'LIKE', 'TAP%')->first();
if(isset($material->Description)) {
return $material->Description;
}
return '-';
}
and as last the view
<table class="table table-striped table-bordered no-width">
<thead>
<tr>
<th>Order nummer</th>
<th>SKU</th>
<th>Omschrijving</th>
<th>Aantal</th>
<th>Datum</th>
<th>Deadline</th>
<th>Materiaal</th>
<th>DXF?</th>
</tr>
</thead>
<tbody>
#foreach($shopOrders as $shopOrder)
<tr>
<td>{{ $shopOrder->ShopOrderNumber }}</td>
<td>{{ $shopOrder->ItemCode }}</td>
<td>{{ str_replace('Car Mats', '',$shopOrder->Description) }}</td>
<td>{{ $shopOrder->PlannedQuantity }}</td>
<td>{{ $shopOrder->PlannedStartDate }} </td>
<td>{{ $shopOrder->PlannedDate }}</td>
<td>{{ $shopOrder->getMaterial() }}</td>
<td>{{ $shopOrder->hasDxf() }}</td>
</tr>
#endforeach
</tbody>
</table>
{{ $shopOrders->total() }}
{{ $shopOrders->appends(['material' => Request::get('material')])->render() }}
I expect 1 page from pagination with orders/nesten?material=Saxony%20Zwart&page=1 as url since that material has 9 orders.
But currently it still has 151 pages, the same as just going to orders/nesten.
From what i see you're fetching all records from database and then filter them with Collection filter. Pagination is build from database query results, so you should update your query to do the filtering.
Update
Create abstract filter class
namespace App\Http\Filters;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
class AbstractFilter
{
protected $builder;
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function apply(Builder $builder)
{
$this->builder = $builder;
foreach($this->filters() as $name => $value) {
if(method_exists($this, $name)) {
call_user_func_array([$this, $name], array_filter([$value]));
}
}
return $this->builder;
}
public function filters()
{
return $this->request->all();
}
}
Extend that class for your request (NOTE - method names here are the request parameters for filters):
namespace App\Http\Filters;
class OrdersFilter extends AbstractFilter
{
public function material($value = null)
{
if (!is_null($value)) {
// return modified query here (return $this->builder->where....)
}
}
}
Add scope to your model (in ShopOrder model):
public function scopeFilter($query, OrderFilters $filter) {
return $filter->apply($query);
}
Update your query like this:
$orders = ShopOrder::whereLike('ItemCode', 'CM%')
->whereNull('Exact')
->whereNull('Nesting')
->where('IsOnHold', '!=', 1)
->where('ShopOrderRoutingStepPlanCount', '!=', 0)
->filter(new OrdersFilter($request))
->paginate(50);
And you can skip all collection filtering. Also you can add more filter params to OrdersFilter class.
NOTE: i wrote everything without testing, so there might be some minor errors. Also I haven't wrote materials filter without having a database structure, but your Model methods could be better.
UPDATE
for filter materials method i would use something like this (not 100% if it works, haven't tested):
public function material($value = null) {
if (!is_null($material)) {
return $this->builder->having('', function($query) use ($value) {
return $query->where('ItemCode', 'LIKE', 'TAP%')
->where('description', '=', $value);
})
->having('routingStepPlans', function($query) {
return $query->where('LineNumber', ShopOrder::timeTransactions()->count() + 1)
->where('description', '=', 'Nesten');
});
}
}
so that your pagination continues but keep your search
{{ $shopOrders->appends(Request::except('page'))->links() }}

Laravel : load objects on many level

I have the following tables :
orders : id, etc...
order_lines : id, order_id, product_id, etc...
products : id, name, etc...
Foreign keys are defined.
My Laravel Models are defined as :
class Order
public function orderLine()
{
return $this->hasMany('App\OrderLine');
}
class OrderLine
public function order()
{
return $this->belongsTo('App\Order');
}
public function product()
{
return $this->belongsTo('App\Product');
}
class Product
public function orderLine()
{
return $this->hasMany('App\OrderLine');
}
I've tried many things, but nothing is working. Here is the best solution for me, but it's not working.
class OrderController
public function show($id)
{
$user = Auth::user();
$order = Order::where('user_id', '=', $user->id)->with(['orderLine.product'])->findOrFail($id);
return view('layouts/order/index', compact('order'));
}
I struggle to display the following data in the view :
#foreach($order->orderLine as $key => $orderLine)
<tr>
<td>{{$orderLine->product->name}}</td>
<tr>
#endforeach
Product object is not loaded. I want to display the product name in the above loop.
Try to do like this:
public function show($id)
{
$user = Auth::user();
$order = Order::with(['orderLines', 'orderLines.product'])
->where('user_id', '=', $user->id)
->findOrFail($id);
return view('layouts/order/index', compact('order'));
}
class OrderLine
public function order()
{
return $this->belongsTo(\App\Order::class, 'order_id');
}
public function product()
{
return $this->belongsTo(\App\Product::class, 'product_id');
}
class Order
public function orderLines()
{
return $this->hasMany(\App\OrderLine::class);
}
Change name of orderLine to orderLines because order has many orderLines.
And in your blade:
#foreach($order->orderLines as $orderLine)
<tr>
<td>{{$orderLine['product']->title}}</td>
<tr>
#endforeach
Hello Dezaley and welcome to StackOverflow!
Let's investigate your problem.
As far as I can see you are selecting the model in the wrong way. Let me help you:
$order = Order::where(['id' => $id, 'user_id' => $user->id])->with('orderLine.product')->firstOrFail();
The answer from mare96, who was very friendly to help me, is working. However, I found out someting.
You can implement as (mare96 solution)
public function show($id)
{
$user = Auth::user();
$order = Order::with(['orderLines', 'orderLines.product'])
->where('user_id', '=', $user->id)
->findOrFail($id);
return view('layouts/order/index', compact('order'));
}
#foreach($order->orderLines as $orderLine)
<tr>
<td>{{$orderLine['product']->title}}</td>
<tr>
#endforeach
In the view, I don't like the array syntax "$orderLine['product']->title". The following solution without the array is also working.
Solution is below :
public function show($id)
{
$user = Auth::user();
$order = Order::with('orderLines', 'orderLines.product')
->where('user_id', '=', $user->id)
->findOrFail($id);
return view('layouts/order/index', compact('order'));
}
#foreach($order->orderLines as $orderLine)
<tr>
<td>{{$orderLine->product->title}}</td>
<tr>
#endforeach
In fact, my issue was that product was defined to null in the model, so Product was always null in the view.
Class OrderLine extends Model {
public $product = null
I remove line "public $product = null" and it's working as expected. Thanks to the people who helped me.
give it a try -
#foreach($order as $ordr)
<tr>
<td>{{$ordr->product_id->name}}</td>
<tr>
#endforeach

Trying to get property of non-object when using One to Many relationship in Laravel

So I keep getting this error when trying to get the name of the user who created a post.
My models look like this:
class User extends Authenticatable {
use Notifiable, CanResetPassword;
public function posts() {
return $this->hasMany('App\Post');
}
}
&
class Post extends Model {
public function user() {
return $this->belongsTo('App\User', 'user_id');
}
}
I try to display the name by doing this in my view:
#foreach($posts as $post)
<tr>
<td>{{ $post->user->name }}</td>
</tr>
#endforeach
And my controller looks like this:
public function getAdminIndex() {
$posts = Post::orderBy('id', 'desc')->get();
$comments = Comment::all();
$likes = Like::all();
$users = User::all();
return view('admin.index', ['posts' => $posts, 'comments' => $comments, 'likes' => $likes, 'users' => $users]);
}
Can anyone please tell me what I'm doing wrong?
Thank you very much!
It means not all posts have user, so do something like this:
<td>{{ optional($post->user)->name }}</td>
Or:
<td>{{ empty($post->user) ? 'No user' : $post->user->name }}</td>

Laravel displaying many to many relationship items

I have set up a many to many relationship in Laravel and have the database table populated with data. The relationship setup looks like this...
users.php
---------
public function houses()
{
return $this->belongsToMany('App\House')
->withTimestamps();
}
house.php
---------
public function users()
{
return $this->belongsToMany('App\User')
->withTimestamps();
}
In my /house/show.blade.php I am trying to display the saved connections like this...
$houses = House::with('App\User')->all();
foreach ($houses as $house) {
echo 'Found House';
}
It is giving me an error saying that $houses can not be found. Where am I going wrong?
You should indicate the relationship in the with method like this :
$houses = House::with('users')->get();
And one more thing it's better to get houses in the controller and pass them to the view :
$houses = House::with('users')->get();
return view('someView')->withHouses($houses);
And in the view do it like this :
#foreach ($houses as $house)
{{ $house->addres }}
#endforeach
To get only the houses taht has the users try this :
$houses = House::has('users')->get();
And to add some conditions on the users you can do it like this :
$houses = House::whereHas('users', function ($query) {
$query->where('name', 'some user name'); // to add some conditions on the user :)
})->get();
You should try this:
$houses = House::with('users')->get();
foreach ($houses as $house) {
echo 'Found House';
}
OR
In controller:
use House;
$houses = House::with('users')->get();
return view('someView',compact('houses'));
In Blade file:
#foreach ($houses as $house)
{{ $house->name }}
#endforeach

Two tables join data passing to view in laravel

need to get data from status table in view. Tried to put alias, googled over 3 hours, I'm lost. Any ideas how?
Controler code:
$action= DB::table('actionplan')
->join('status','actionplan.status','=','status.id')
->select('status.name as testas','actionplan.*')
->where([['user_id','=',$name],['done','<>',1]])->get();
View code:
#foreach($teams as $item)
<th scope="row">1</th>
<td>{{$item->name}}</td>
<td>{{$item->start_date}}</td>
<td>{{$item->end_date}}</td>
<td>{{$item->comment}}</td>
<td>{{$item->status()->name}}</td>
You should really implement models for your database tables. While this isn't the advice you're asking for, it will greatly simplify your queries in this regard.
Your ActionPlan.php model:
use Illuminate\Database\Eloquent;
class ActionPlan extends Model
{
protected $table = 'actionplan';
public function status()
{
return $this->hasOne(App\Status::class, 'id', 'status');
}
}
Your Status.php model:
use Illuminate\Database\Eloquent;
class Status extends Eloquent
{
protected $table = 'status';
}
Your query:
$actions = Action::whereHas('status')
->where('user_id', '=', $name)
->where('done', '<>', 1)
->get();
Or:
$actions = Action::whereHas('status')
->whereUserId($name)
->having('done', '<>', 1)
->get();

Categories