-
-
Save ryangjchandler/1c579774cc2c2c5fda421f3374e4a01c to your computer and use it in GitHub Desktop.
Validating Laravel Console Input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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