Vishal B
Vishal B

Reputation: 653

max() function not working properly in laravel querybuilder

I am trying to get maximum column value of table using query :

$today = Carbon::today();
    $o_no = Prev_order::whereDate('date_time',"=", $today)->max('ord_no');
    if($o_no){
        $o_no = $o_no + 1;
    }
    else{ $o_no = 1; } 

    $orders = order::where('table_no', $request->table_no)
                    ->where('dish', $request->dname)
                    ->first();      
    if($orders != null)
    {
            $qty = $orders->dish_qty + $request->dish_qty;
            $data = [
                'dish_qty' => $qty,
            ];
            $orders = order::where('dish', $request->dname)->update($data);
    }     

return response()->json($todr);

but it is not giving max value after 9, means if max value is 10 it is giving max value as 9... I am not geting what is wrong exactly. actually am increasing value after each submit button i.e order no. when I check previous max value(order no) i added 1 in it and updating new order no. but here when value is 10 it is often adding value as 10 only, when i checked max() function it is giving max value as 9 only, whats wrong exactly.

Upvotes: 1

Views: 2064

Answers (1)

kiran gadhvi
kiran gadhvi

Reputation: 228

It simply means that you are getting data from table first then you are updating order no. So in that case even if order no has changed in database you will not get upgraded order no that is maximum value or else please share some code so that it will help to understand even better.

I don't think there is problem with max function, if you think max function is not working properly then you can try a different query.

DB::table('orders')->where('id', DB::raw("(select max(`id`) from orders)"))->get();

And if you are using Eloquent models.

$order = Orders::whereRaw('id = (select max(`id`) from orders)')->get();

Upvotes: 1

Related Questions