in my controller i have
public function store(Request $request) {
$validator = Validator::make($request->all(), [
"list_img" => "required",
"ge_title" => "required|max:255"
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
if validation fails i got messages -
validation.required
validation.required .....
instead of
ge_title is required
list_img is required
p.s. I have 3 languages on my site and i dont have validation.php file in resources/lang (if it matters)
Try to add the third argument the error messages:
public function store(Request $request){
$validator = Validator::make($request->all(), [
"list_img" => "required",
"ge_title" => "required|max:255"
], [
"list_img.required" => "List img is required",
"ge_title.required" => trans('errors.required'), //if you have multilang. then use trans function
"ge_title.max" => trans('errors.max_title')
]);
if ($validator->fails()){
return redirect()->back()->withErrors($validator)->withInput();
}
}
It is not
$request->query->all()
instead of
$request->all()
for post or something like this ?
Related
I make form by React. After submitted form, I need to validate data from Laravel. Problem is that sending data is diffrent than normal form. So any values from dorm is in array data.
//normal form
$request->title
//sending from React
$request->data['title']
So, look at this code
class articleRequest extends Request
{
public function rulse(){
return [
'title' => 'required',
//other rules
];
}
}
class ArticleController extends Controller
{
public function atoreArticle(articleRequest $request){
Textads::create([
'title'=> $request->data['title'],
//other
]);
}
}
But I have an error that title field is required. Without valdiation everything is ok. How I can solve my problem?
You can try this -
$rules = [
'title' => 'required',
//other rules
];
Validator::make($request->all(), $rules)->validate();
will this work? or $request->all()->data ?
$validator = Validator::make($request->data, [
title'' => 'required'
],[
//custom error message if needed
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'data' => $validator->messages(),
'message' => "error"
], 422);
}
I have a function that updates the data. It receives the data as an array parameter.
I tried use validator make, and also validate helper method but it didn't work because it's only work for requests, and i tried also in validator make as the code below and also 'params.name' but it didn't work.
public function updateCompany(array $params): bool
{
if( Validator::make($params,[
'name'=> 'required|min:3|unique:company',
'email'=> 'required|min:4|unique:company|email'
])) {
return $this->update($params);
}
}
After trying this it didn't give me any error put it ignores my validation rules and update anyway.
Just use
public function updateCompany(Request $request)
then you could do something like this:
$rules = array('name' => 'required',
'email' => 'email|required|unique:users',
'name' => 'required|min:6|max:20');
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return ['status' => 422, 'errors' => $validator->errors()];
}
Laravel 5.5
public function register(Request $request) {
request()->validate([
'email' => 'required:email'
'password' => 'required|min:6'
]);
return response()->json(["message" => "Hello World"]);
}
If validator is fails, not giving error messages. Redirecting main page.
If the code you're using redirects you to the previous page when validation fails, it means that you didn't tell the server what kind of response you want to receive.
Set a proper header to get JSON. It will make the validator send JSON in response. For example:
$.ajax({
headers: {
Accept : "application/json"
},
...
});
Then this code will work as expected:
public function register(Request $request)
{
$request->validate([
'email' => 'required:email'
'password' => 'required|min:6'
]);
return response()->json(["message" => "Hello World"]);
}
I had the same problem when testing my rest api in Postman application.
if we don't want to modify our current code of laravel redirect repose, we have to put Accept:-application/json and ContentType:-application/json
For modifying code in controller class file, i did it like this and got the json response instead of redirecting to home page.
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors());
} else {
// do something
}
}
before it looks like below codes it was redirecting to home page
This is validator function
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
}
public function register(Request $request)
{
// Here the request is validated. The validator method is located
// inside the RegisterController, and makes sure the name, email
// password and password_confirmation fields are required.
$this->validator($request->all())->validate();
// A Registered event is created and will trigger any relevant
// observers, such as sending a confirmation email or any
// code that needs to be run as soon as the user is created.
event(new Registered($user = $this->create($request->all())));
// After the user is created, he's logged in.
$this->guard()->login($user);
// And finally this is the hook that we want. If there is no
// registered() method or it returns null, redirect him to
// some other URL. In our case, we just need to implement
// that method to return the correct response.
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
You can do this like this :
$validator = Validator::make($request->all(), [
'email' => 'required|email', //use pipe here to apply multiple validations rules and add a ','
'password' => 'required|min:6'
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()]);
}
return response()->json(["message" => "Hello World"]);
The validation is working well, but, $request->validate() will redirect you to the previous page. I recommend you to manually create your validations:
Manually Creating Validations.
You could do something like this:
use Illuminate\Http\Request;
use Validator;
class YourClass extends Controller{
public function yourFunction(Request $request) {
$validator = Validator::make($request->all(),[
'field_1' => 'rule1|rule2',
'field_2' => 'rule1|rule2'
]);
if ($validator->fails()) {
return response()->json($validator->errors());
} else {
/*Something else*/
}
}
}
try this, hope this code can help you
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
I have a small question. I create simple API using Laravel. When I use validation and if it fails, I got a common message:
{
"result": false,
"message": "The given data failed to pass validation.",
"details": []
}
But how can I get details about which field fails and why like that:
{
"result":false,
"message":"The given data failed to pass validation.",
"details":{
"email":[
"The email field is required."
],
"password":[
"The password must be at least 3 characters."
]
}
}
My code in controller looks like this:
protected function validator(array $data)
{
$validator = Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:3',
]);
return $validator;
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role_id' => 2
]);
}
It is better to handle the validator within the same process, like this:
public function register(Request $request){
$validator = Validator::make($request->all(),[
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
if($validator->fails()){
return response()->json([
"error" => 'validation_error',
"message" => $validator->errors(),
], 422);
}
$request->merge(['password' => Hash::make($request->password)]);
try{
$user = User::create($request->all());
return response()->json(['status','registered successfully'],200);
}
catch(Exception $e){
return response()->json([
"error" => "could_not_register",
"message" => "Unable to register user"
], 400);
}
}
You should make sure you're sending the request with the Accept: application/json header.
Without that - Laravel won't detect that it's an API request,
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
check the documentation
I used validate in my project:
1.I created app/http/requests/CreateUserRequestForm.php
public function rules()
{
return [
"name" => 'required',
"address" => 'required',
"phnumber" => 'required|numeric',
];
}
public function messages()
{
return [
'name.required' => 'Please Enter Name',
'addresss.required' => 'Please Enter Address',
'phnumber.required' => 'Please Enter PhNumber'
];
}
call the RequestForm in controller
use App\Http\Requests\CreateUserRequestForm;
public function createUser(CreateUserRequestForm $request)
{
// create
$user= UserModel::create([
'name' => $request->input('name'),
'address' => $request->input('address'),
'phnumber' => $request->input('phnumber')
]);
return response()->json(['User' => $user]);
}
Try this i didn't try but it should be work for you.
You may use the withValidator method. This method receives the fully
constructed validator, allowing you to call any of its methods before
the validation rules are actually evaluated.
take reference from here. laravel validation
/**
* Configure the validator instance.
*
* #param \Illuminate\Validation\Validator $validator
* #return void
*/
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add('email', 'Please enter valid email id');
}
});
}
Try this:
public function create(){
// ------ Validate -----
$this->vallidate($request,[
'enter code here`name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:3'
]);
// ------ Create user -----
$user = User::create(['name' => $request->name']);
return response()->json([
'message' => "success",
'data' => $user``
]);
}
I have tried almost every possibility but Email Validation is not working in form validation and it takes to MySQL exception of unique email required.
public function rules()
{
return [
'email'=>"required|email|unique:users,email",
'password' => "required|min:6",
'first_name' => "required",
'last_name'=>"required",
'country'=>"required",
'city'=>"required",
'is_willing_to_relocate'=>"required",
'min_gross_salary'=>"required|integer|min:0",
'max_gross_salary'=>"required|integer|min:0",
'skills'=>'required|json|objCount',
'languages'=>'required|json|objCount',
'professions'=>'required|json|objCount',
'cities'=>'required_if:is_willing_to_relocate,yes|json|objCount'
];
}
I think you should validate like this:
public function postSignUp(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:users' ,
]);
}