Laravel Command: Return error msg and exit code on 1-line

·

1 min read

Hi guys,

A small tip for your weekend. For Laravel's devs out there.

Ever wonder how can I write the error and then stop the command immediately (with an error code) in 1 line?

Lemme show you how :v

Today our code looks like this:

public function handle(): int
{
    if ($somethingWentWrong) {
        $this->error('Uh oh, unexpected error');

        return 1;
    }
}

Let's add a bit of cosmetic for it. Simply:

if ($somethingWentWrong) {
    return $this->error('Uh oh, unexpected error') || 1;
}

// or
if ($somethingWentWrong) {
    return $this->error('Uh oh, unexpected error') ?: 1;
}

In 1 line only, awesome!

Explanation

->error or ->info or ->warn ,... They are returning the void type.

|| (OR) or ?: (ternary operator) recognizes the void type as a falsy value.

\=> 1 will be returned in the code example above!

Conclusion

Enjoy!