Back to blog
Mar 13, 2024
2 min read

Double-check your Laravel validations and casts for data type shorthands.

Laravel requires full data type terms (boolean, integer) for casts and validation rules, and using shorthand types like bool or int can lead to unnoticed bugs since they’re not detected by IDEs or static analysis tools.

I stumbled across this out-of-the-blue when testing for attribute-casting on a Model property, having realised I put bool instead of boolean, both by mistake and out of habit as PHP requires the short-hand of data-types whereas Laravel requires the full term.

So far I’ve found this to be an issue with int vs integer and bool vs boolean, and an issue only in validation rules and Model attribute casts.

For example, below shows attribute casting and validation that is invalid yet your IDE nor services will detect it.

protected $casts = [
    'is_admin' => 'bool',
    'age' => 'int'
];

$request->validate([
    'is_admin' => 'required|bool',
    'age' => 'required|int',
]);

A valid example;

protected $casts = [
    'is_admin' => 'boolean',
    'age' => 'integer'
];

$request->validate([
    'is_admin' => 'required|boolean',
    'age' => 'required|integer',
]);

Detecting this can be easily missed given that these are within strings and outside of PHP, and I’ve yet to find any services that detect this bug, including the likes of laravel-enlightn or sonarqube, and although it’s somewhat minor it can lead to unintentional side-effects and assumptions that can have consequences.

To mitigate this, I hope Laravel can either add alias support or throw an exception.