I have a code:
$orders = Order::all();
$allorders = $orders->count();
$deliveryQuery = $orders->where('status', '=', '8')->select(DB::raw('AVG(updated_at) as order_average'))->first();
I get error:
Method select does not exist.
How I can fix it? My code is working, if I do:
$deliveryQuery = Order::where('status', '=', '8')->select(DB::raw('AVG(updated_at) as order_average'))->first();
But this not good, I want 1 query, but not 2..
UPDATE:
$orders->where('status', '=', '8')->avg('updated_at')->first();
I can use this code? But it not working..Get error:
Object of class Illuminate\Support\Carbon could not be converted to int
You can try this..
$query = Order::query();
$orders = clone $query;
$orders = $orders->all();
$allorders = $orders->count();
$deliveryQuery = $query->where('status', '=', '8')->select(DB::raw('AVG(updated_at) as order_average'))->first();
similar question can be found here
The all() method return a Collection. You can then use Collection methods on the result, but where() and select() are methods of the QueryBuilder class.
$query = Order::query(); // You can get the query builder this way.
$orders = Order::all(); // equivalent to $query->get(); => return a Collection
$orderCount = Order::count(); // equivalent to $query->count();
$orderCount = $orders->count(); // here $orders is a Collection and the count() method is from the Collection class
When you call avg(), you're calling it from the Collection class. But it can only work on number, and updated_at attribute is parsed to a Carbon date by Laravel.
Your code could be :
$query = Order::query();
$orders = $query->get();
$allorders = $query->count();
$deliveryQuery = $query->where('status', '=', '8')->select(DB::raw('AVG(updated_at) as order_average'))->first();