I’m creating a laravel custom Uppercase.php rule in my app/Rules namespace to check whether the title submitted starts with a capital letter if not should throw an error/ fail.
class ArticleController extends Controller
{
public function store(Request $request)
{
$request->validate([
'title' => ['required', new Uppercase()]
]);
Article::create(['title' => $request->title]);
}
}
this is the code in the Uppercase.php class.
am trying to check if the title first character is capitalised
use Closure;
use IlluminateContractsValidationValidationRule;
class Uppercase implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (ucfirst($value) !== $value) {
$fail("The $attribute must start with an uppercase letter.");
}
}
}
more details
when running the test, still fails
3
Answers
You can change validation with below one. Value is first converted to lowercase and then applied
ucfirst
I am wondering why do you create custom validation rule to check first character is capital or not.
While storing value to database you can apply same conversion as below.
make sure you import
IlluminateSupportStr
You can use like this too.
and in controller
You can use mutators in your model to ensure that the title value is saved as you wish in the database, instead of using validation or a form request.
Here are the mutators in the model for Laravel 8 and before:
And for Laravel 9 and after, you can use: