Skip to content

Instantly share code, notes, and snippets.

@ryangjchandler
Last active May 16, 2023 12:54
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryangjchandler/1c579774cc2c2c5fda421f3374e4a01c to your computer and use it in GitHub Desktop.
Save ryangjchandler/1c579774cc2c2c5fda421f3374e4a01c to your computer and use it in GitHub Desktop.
Validating Laravel Console Input
<?php
namespace App\Console\Commands\Concerns;
use Illuminate\Support\Facades\Validator;
trait WithInputValidation
{
public function askWithValidation(
string $message, array $rules = [], string $name = 'value'
) {
$answer = $this->ask($message);
$validator = Validator::make([
$name => $answer,
], [
$name => $rules,
]);
if ($validator->passes()) {
return $answer;
}
foreach ($validator->errors()->all() as $error) {
$this->error($error);
}
return $this->askWithValidation($message, $rules, $name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment