Mr Pixel
Mr Pixel

Reputation: 100

Laravel Validation Rules

My need is just Laravel validation Rules.I want to use Laravel validation to check variables. and show custom errors by returning string in controller.(I dont use view, blade, session,... I just return string)

if(strlen($username) < 4) return '{"r": "US","msg": "username is short"}';
if(strlen($username) > 64) return '{"r": "UL","msg": "username is long"}';
if(strlen($address) > 200) return '{"r": "A","msg": "wrong address"}';  

I want something like this:

if($validation->username->min has error)
     return 'string:username is short';

if($validation->address->max has error)
     return 'string:address is long';

if($validation->username->unique has error)
     return 'string:username already exists';

Upvotes: 0

Views: 1170

Answers (1)

Karim Geiger
Karim Geiger

Reputation: 662

Have a look at the official documentation of validation in Laravel. You don't have to handle every case manually. Validator::make() will generate a validator object for you. The first parameter will take your data as an associative array. The second argument will define all rules as desired. As a third, optional parameter you may define alternative error messages if you don't like the default ones. The will be returned in the errors() method in case something isn't valid.

$validator = Validator::make($yourDataArray, [
    'username' => 'min:4|max:64|exists:table,username',
    'address' => 'max:64'
], [
    'min' => ':attribute is too short.',
    'exists' => ':attribute already exists.
]);

if ($validator->fails()) {
    return $validator->errors()->all();
}

If you don't want to get an array with all errors at once, you can get the state of each field like so:

if ($validator->errors()->has('username')) { // Username field is invalid
    return $validator->errors()->first('username'); // Get the first error
}

And if you want to know what rule exactly failed, you can use something like that:

if(isset($validator->failed()['username']['Max'])) {
    return 'Username is too long.';
}

Upvotes: 1

Related Questions