To prevent automatic casting during database queries and validations in Laravel, you can use the whereRaw method to specify the query condition as a raw SQL expression. This will prevent Laravel from automatically casting the value to an integer.
Here's an example of how you can modify your validation rule to force Laravel to query the database value as a string:
'exists:\MyModel\KTR,name' => function ($attribute, $value, $fail) {
$query = \MyModel\KTR::whereRaw('CAST(name AS nvarchar) = ?', [$value]);
if (!$query->exists()) {
$fail('The selected value is invalid.');
}
},
In this example, we're using the whereRaw method to compare the name column with the provided value using a raw SQL expression. The CAST(name AS nvarchar) ensures that the comparison is done as a string.
You can replace the existing validation rule with this custom rule in your validation logic.
Note: Make sure to replace \MyModel\KTR with the correct namespace and class name of your model.