skip to Main Content

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


  1. You can change validation with below one. Value is first converted to lowercase and then applied ucfirst

    use Closure;
    use IlluminateContractsValidationRule;
    
    class Uppercase implements Rule
    {
        public function passes($attribute, $value)
        {
            $firstCharOfTitle = Str::substr($value, 0, 1);
            return Str::ucfirst($firstCharOfTitle) === $firstCharOfTitle;
        }
    
        public function message()
        {
            return 'The :attribute must start with an uppercase letter.';
        }
    }
    

    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.

    Article::create(['title' => Str::ucfirst($request->title)]);
    

    make sure you import IlluminateSupportStr

    Login or Signup to reply.
  2. You can use like this too.

    use Closure;
    use IlluminateContractsValidationRule;
    
    class Uppercase implements Rule 
    {
        public function passes($attribute, $value)
        {
            if (empty($value)) {
                return false;
            }
    
            $firstCharacter = $value[0];
            return $firstCharacter === strtoupper($firstCharacter);
        }
    
        public function message()
        {
            return 'The :attribute must start with an uppercase letter.';
        }
    }
    

    and in controller

    class ArticleController extends Controller
    {
        public function store(Request $request)
        {
            $request->validate([
                'title' => ['required', new Uppercase()]
            ]);
    
            Article::create(['title' => $request->title]);
        }
    }
    
    Login or Signup to reply.
  3. 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:

    class Article extends Model
    {
        public function setTitleAttribute($value)
        {
            $this->attributes['title'] = ucfirst($value);
        }
    }
    

    And for Laravel 9 and after, you can use:

    use IlluminateDatabaseEloquentCastsAttribute;
    
    class Article extends Model
    {
        /**
         * Set the article's title.
         *
         * @return IlluminateDatabaseEloquentCastsAttribute
         */
        protected function title(): Attribute
        {
            return Attribute::make(
                set: fn ($value) => ucfirst($value),
            );
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search