custom validation message in laravel 8 - laravel

how to give custom laravel message in my coding i am new in laravel
$validatedData = $r->validate([
'preference' => 'required',
'objective_1' => 'required',
'objective_2' => 'required',
'objective_5' => 'required',
]);
if (empty($r->session()->get('sessForm'))) {
$r->session()->put('sessForm', $validatedData);
} else {
$sessForm = $r->session()->get('sessForm');
$r->session()->put('sessForm', $sessForm);
}

You can use custom validator. Check the documentation. You can get messages from $errors variable in blade template.
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
], [
'title.required' => 'Title required custom message',
'title.unique' => 'Title unique custom message',
// ...
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
If you want to send redirect with data. You can use
redirect()->route('route')->with('data', 'test');
You can get after redirect
session('data')

Related

Laravel - How to return the error message

I am trying to validate the form using this way:
// Start validation
$validator = Validator::make($request->all(), [
'project_token' => 'required',
'user_id' => 'required',
'competitor_name' => 'required',
'competitor_domain' => ['required','regex:/^(?!(www|http|https)\.)\w+(\.\w+)+$/'],
'status' => 'required',
]);
// If validation is not sucessfull
if( $validator->fails() ) {
return response()->json([
'success' => false,
'message' => $validator->withErrors($validator)
], 200);
} else {
....
}
If the validation is failed I want to get the error messages in the message key. How can I get the error messages ? Its showing me an error message:
Method Illuminate\Validation\Validator::withErrors does not exist.
You have to use a validator error like this
if( $validator->fails() ) {
return response()->json([
'success' => false,
'message' => $validator->errors()
], 200);
}
Or
$validator->errors()->all(); # as a Array
Try this, It will return proper validation message and check the validation on defined field.
$request->validate([
'project_token' => 'required',
'user_id' => 'required',
'competitor_name' => 'required',
'competitor_domain' => ['required','regex:/^(?!(www|http|https)\.)\w+(\.\w+)+$/'],
'status' => 'required',
], [
'project_token.required' => 'Please Generate Project token'
]);
in your blade file if you add this condition after each element then if any validation error acure then it will show in front with custom message
#if ($errors->has('project_token'))
<span class="text-danger">{{ $errors->first('project_token') }}</span>
#endif

Laravel 8: How to send validation response in JSON format using postman

I have this validation, how can I return an error response in postman?
please help guys.
$rules = [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
];
$validator = $this->validate($request, $rules);
$data = $request->all();
use Illuminate\Support\Facades\Validator;
Then write validation like
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
]);
if ($validator->fails()) {
return response()->json([
'message' => 'Invalid params passed', // the ,message you want to show
'errors' => $validator->errors()
], 422);
}

How can I use fails method validation in controller

controller validator in laravel :
$validationController = $this->validate(request(), [
'title' => 'min:100',
'text' => 'required',
'image' => 'required',
]);
and we can make validator with :
$validationNormaly = Validator::make(request(), [
'title' => 'min:100',
'text' => 'required',
'image' => 'required',
]);
and i can't use $validationController->fails(). how can i use it?
The first validation that you mentioned will fail automatically as designed by the laravel code base.
The Validator::make() i typically use when doing ajax requests and such to the controller method. You will need to run the validation fails method to invoke the failed response like so:
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
You Can Use :
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();
take advantage of the automatic redirection with error messages

How can i pass only one message for all fields

This is code of register function which generate error of success and failure.
public function register(Request $request) {
$validator = Validator::make($request->all(),
[
'user_type' => 'required',
'fname' => 'required',
'lname' => 'required',
'dob' => 'required',
'phone' => 'required',
'gender' => 'required',
'uname' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['failed'=>$validator->errors()], 401); }
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('AppName')->accessToken;
$success['status'] = true;
$success['data'] = [$user];
$success['message'] ="User created successfully!";
// return response()->json([
// "message" => " record created"
// ], 201);
return response()->json($success, $this->successStatus);
}
This is my output
1.All error message show in one line..This is my main point..But i want to actually this message of This image...How can i do that?
2.Second thing in API if any user put same email id api give json error not laravel error..
Try this:
return response()->json(['status'=> False, 'msg' => 'This is not successful'], 401);
You can pass custom json in response instead of validator response.
For checking if email exists update the validation like this:
'email' => 'required|email|unique:users,email',
where users is your table name and email is your column name
You just need to replace your code
if ($validator->fails()) {
return response()->json(['failed'=>$validator->errors()], 401);
with
if ($validator->fails()) {
return response()->json(['status'=> 'False', 'msg' => 'This is not sccessfully'], 401);

return validation errors from laravel controller to vue

everybody, I need to return error validation for this validation code to vue
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();
I have tried
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();
if ($validator->fails()) {
return $this->sendError('error validation', $validator->errors());
}
but did't work for me
List errors
$validator->messages();

Resources