Laravel 5.4: groupBy on for-loop not working as expected
Here is my controller first it’s very important to see this controller
public function index( Request $request ) {
$dateFrom = $request->get( 'dateFrom' );
$dateTo = $request->get( 'dateTo' );
$status = $request->get( 'orderState' );
$orders = ( new OrderList() )
->whereHas( 'orderDetail', function ( $query ) {
$query->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id );
} )
->with( 'deliveryList' )
->when( $dateFrom, function ( $query ) use ( $dateFrom, $dateTo ) {
$query->whereBetween( 'created_at', [ $dateFrom, $dateTo ] );
} )
->when( $status, function ( $query ) use ( $status ) {
$query->where( 'order_state_id', $status )->get();
} )->get();
//Order Status
$orderStates = OrderState::listsTranslations( 'states' )->pluck( 'states', 'id' )->toArray();
return view( 'supplierComponents.order_list', compact( 'orders', 'orderStates' ) );
}
and here is also the Models for OrderList
and OrderDetail
class OrderList extends Model {
protected $fillable = [
......
......
];
public function orderDetail() {
return $this->hasMany( OrderDetail::class, 'order_id' );
}
public function ....
....................
}
}
class OrderDetail extends Model {
protected $fillable = [
......
......
];
public function orderId() {
return $this->belongsTo( OrderList::class, 'order_id' );
}
public function productId() {
return $this->belongsTo( Product::class, 'product_id' );
}
}
Now I am trying to do groupby in the blade file
@foreach($orders as $order)
@foreach($order->orderDetail->groupBy('product_id') as $items)
<tr>
<td>{!! $items->sum('quantity') !!}</td>
<td>{!! $items->first()->product_name !!}</td>
<td>{!! $items->first()->product_id !!}</td>
</tr>
@endforeach
@endforeach
Now the results of this array is coming like
-------------------------------------------
product-name | quantity | product-id |
-------------------------------------------
Coffey | 2 | 15 |
Coffey | 1 | 15 |
Coffey | 1 | 15 |
tea | 3 | 22 |
tea | 2 | 22 |
tea | 1 | 22 |
-------------------------------------------
which I need it to be something like
-------------------------------------------
product-name | quantity | product-id |
-------------------------------------------
Coffey | 4 | 15 |
tea | 6 | 22 |
-------------------------------------------
How to achieve this
from Laravel Questions and Answers https://laravelquestions.com/php/laravel-5-4-groupby-on-for-loop-not-working-as-expected/
via Lzo Media
No comments:
Post a Comment