skip to Main Content

There was a problem. Previously, the share_price column was a float, after which we had to change it to a string, because the client requested the use of not only floats, but also words.

To display the minimum and maximum values in the filter, use the min and max function.
But since appeared string, max value is now always string.
How to convert column to float in max wrapper?

$companyList = $companyList->get();
$maxValue = $companyList->max('share_price');

UPDATE

It seems you misunderstood me a bit. This does not mean the conversion of the already obtained value, but when selecting the max value.

Example:

  • 1.52
  • 2.43
  • 3.35
  • STRING

When i get ->max() – i get STRING, but need to get 3.35

4

Answers


  1. You can try floatval function of PHP.

    floatval($string);
    

    or you can also cast your string value into float like below:

    (float)$string;
    
    Login or Signup to reply.
  2. Cast $maxValue as int or float

    $int = (int)$num;
    $float = (float)$num;
    

    or the hacky way

    $maxValue = $companyList->max('share_price') + 0;
    
    Login or Signup to reply.
  3. Since you’re already using a collection, I’d suggest using filter to filter out all non-numeric items.

    $companyList->get()
        ->filter(fn ($value, $key) => is_numeric($value->share_price))
        ->max('share_price');
    
    Login or Signup to reply.
  4. The IlluminateSupportTraitsEnumeratesValues::max method accepts only one argument that can be either:

    • a string that acts as the key to check in the collection
    • or a callable (a function) that you may use to filter out strings in your case.

    In your case, you can use a callback function that removes the strings, or precisely, treats the strings as null.

    /** we will simply tell the "max" method to treat strings as "null" */
    $maxValue = $companyList->get()->max(fn($value) => is_string($value) ? null:$value);
    

    The above code will:

    • return the maximum number if at least 1 integer/float is found in the collection.
    • return null if the collection is empty or contains only strings.

    The code sample above DOES NOT convert strings to their float/integer representation and even if you have a valid, castable string in your collection (like "100") it will be treated as null.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search