Search code examples
phplaravellaravel-5laravel-4laravel-5.3

Laravel groupBy not working properly


I want to make one group by depend on my custom condition.But I am not sure my way is right or not.

My code

$cderList = $cderListQuery->groupBy('cder_id')
    ->groupBy('name')
    ->groupBy(function ($query) {
        if(!is_null($this->hp) || !is_null($this->hp))
        {
            $query->groupBy('Value_Float');
        }

     })
    ->orderBy('introduced', 'DESC')
    ->limit(20)
    ->get();

Error Details

strtolower() expects parameter 1 to be string, object given
in Grammar.php (line 58)

at HandleExceptions->handleError(2, 'strtolower() 
expects parameter 1 to be string, object given', 
'/home/vendor/laravel/
framework/src/Illuminate/Database/Grammar.php', 
58, array('value' => object(Closure), 'prefixAlias' => false))

Solution

  • Use the when Conditional clause (From laravel documentation) I guess what you want to do is order by 'Value_Float' only when a condition is true

    //Set the condition here
    $condition = !is_null($this->hp) || !is_null($this->hp);
    
    $cderList = $cderListQuery->groupBy('cder_id')
        ->groupBy('name')
        ->when($condition, function($query){
            //This segment will only run if condition is true
            return $query->groupBy('Value_Float');
        })
        ->orderBy('introduced', 'DESC')
        ->limit(20)
        ->get();