Home > Net >  How can I write this code less and better in Laravel?
How can I write this code less and better in Laravel?

Time:03-04

How can I write this code less and better in Laravel? I am writing this code to remove the / r character in the input text and also to calculate the number of characters in the text.

$removeRchar = Str::remove("\r", $request['message']);
    $length = Str::length($removeRchar);
    if ($length <= 70) {
        $pages = 1;
    } else {
        $pages = ceil($length / 70);
    }

CodePudding user response:

You could create a Stringable

$length = Str::of($request['message'])
    ->remove('\r')
    ->length();

$pages = ceil($length / 70);

If you don't want an extra page when you have a lenght of 70, 140 etc. you should add a check. For example:

$pages = $lenght % 70 === 0 
    ? $lenght / 70
    : ceil($length / 70);

CodePudding user response:

You can also use a ternary operator to minify your code.

$length = strlen(Str::remove("\r", $request['message']))

$pages = $length <= 70 ? 1 : ceil($length / 70)

  • Related