I want to add a validation on a form. My actual form works, here it is:
public function store(Request $request, $id)
{
$this->validate($request, [
'subject' => 'required',
'body' => 'required',
]);
// Do something if everything is OK.
}
Now, I want to check if the user is "active" too. So something like:
\Auth::user()->isActive();
And return an error with the other validation errors if the user is not active.
Can I append something to the validator that has no relation with the form itself? I mean I want to add an error to the other errors if the user is not active.
That code is only validating the request variable (first argument of validate() function). So you will have to put someting in the request to validate it. It applies the rules to the object/array given.
$request->is_active = Auth::user()->isActive();
$this->validate($request, [
'subject' => 'required',
'body' => 'required',
'is_active' => true //or whatever rule you want
]);
Anyways, I never tried that so not sure it will work. The usual way is to do an if
if ( !Auth::user()->isActive() ) {
return redirect->back()->withErrors(['account' => 'Your account is not active, please activate it']);
}
//continue here
Related
This is most likely a duplicate question but I have been looking for solutions and can't seem to find one that fixes the issue I have. I have created a function called validateRequest which validates all the fields. This function is then called in store function $post = Post::create($this->validateRequest()); I have made sure in the HTML form enctype="multipart/form-data" has been included, but every time a submit a new entry that errors appear. Not sure if I am using the return tap method correctly or something else, really appreciate some help thanks.
public function validateRequest()
{
return tap(
$validated = request()->validate([
'title' => 'required|string',
'h1' => 'required|string',
'page_title' => 'required|string',
'meta_description' => 'required|string',
'image' => 'sometimes|files|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
'content' => 'required|string',
'active' => 'integer'
]), function () {
if (request()->hasFile('image')){
request()->validate([
'image' => 'sometimes|files|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
]);
}
// Check if active is ticked
$validated['active'] = isset(request()->active[0]) ? 1 : 0;
// Create slug from title
$validated['slug'] = Str::slug(request()['title'], '-');
});
}
"files" is not a valid validator, use file without "s"
'image' => 'sometimes|files|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
Hope this helps
Laravel throw an exception at $validator->fails() call.
Ok, I just want to create a stateless register method in ApiController.php with Laravel 5.7.
I used the Validator facade to check the sent data.
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()],
Response::HTTP_UNAUTHORIZED);
}
But, when I use xdebug, I see something strange. The fails methods seems throw an exception.
Laravel send an error HTML page with title:
Validation rule unique requires at least 1 parameters.
The route is used in api.php
Route::post('register', 'Api\UserController#register');
Do you have an explanation for this?
Thx for reading.
The syntax for unique rule is unique:table,column,except,idColumn.
So i changed it for you to use the users table.
If you don't want to use the users table change the users part behind unique:
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()],
Response::HTTP_UNAUTHORIZED);
}
For more information on the unique rule see this: https://laravel.com/docs/5.7/validation#rule-unique
In your API request add the following header:
...
Accept: application/json // <-----
This will tell Laravel that you want a response in a json format.
Note: this is different to the Content-type: application/json. The later indicates the format of the data tha is being sent in the body.
hi folks I'm working on Laravel 5.5 and here I need to display validation messages for my API upto now I have done like this
$validator = Validator::make($request->all(),[
'first_name' => 'email|required',
'last_name' => 'nullable',
'email' => 'email|required',
'mobile_no' => 'nullable|regex:/^[0-9]+$/',
'password' => 'required',
]);
if($validator->fails)
{
$this->setMeta('status', AppConstant::STATUS_FAIL);
$this->setMeta('message', $validator->messages()->first());
return response()->json($this->setResponse(), AppConstant::UNPROCESSABLE_REQUEST);
}
Since Laravel 5.5 has some awesome validation features I am looking to validate my request like this
request()->validate([
'first_name' => 'email|required',
'last_name' => 'nullable',
'email' => 'email|required',
'mobile_no' => 'nullable|regex:/^[0-9]+$/',
'password' => 'required',
]);
But I am facing issue here what should I do to check if the validation fails? Like I was doing by if($validator->fails)
In Laravel 5.5, like the documentation mention, the validation process is very easy :
Displaying The Validation Errors :
So, what if the incoming request parameters do not pass the given
validation rules? As mentioned previously, Laravel will automatically
redirect the user back to their previous location. In addition, all of
the validation errors will automatically be flashed to the session.
Again, notice that we did not have to explicitly bind the error
messages to the view in our GET route. This is because Laravel will
check for errors in the session data, and automatically bind them to
the view if they are available.
AJAX Requests & Validation :
In this example, we used a traditional form to send data to the
application. However, many applications use AJAX requests. When using
the validate method during an AJAX request, Laravel will not generate
a redirect response. Instead, Laravel generates a JSON response
containing all of the validation errors. This JSON response will be
sent with a 422 HTTP status code.
So as you said : that means you don't need to put your ifs to handle validation laravel will take care of them itself great :)
here is some syntax that i use
public static $user_rule = array(
'user_id' => 'required',
'token' => 'required',
);
public static function user($data)
{
try{
$rules = User::$user_rule;
$validation = validator::make($data,$rules);
if($validation->passes())
{
}
else
{
return Response::json(array('success' => 0, 'msg'=> $validation->getMessageBag()->first()),200);
}
return 1;
}
catch(\Illuminate\Databas\QueryException $e) {
return Response::json(array('success' => 0, 'msg' => $e->getMessage()),200);
}
}
hope this will help you!
Please add Accept: application/json in you header.
Laravel automatically send an error message with response code.
As per 2019 Laravel 5.8 it is as easy as this:
// create the validator and make a validation here...
if ($validator->fails()) {
$fieldsWithErrorMessagesArray = $validator->messages()->get('*');
}
You will get the array of arrays of the fields' names and error messages.
You can show first error.
if ($validator->fails()) {
$error = $validator->errors()->first();
}
For all error :
$validator->errors()
So I'm learning Laravel, and I'm trying to create a new user in the database using data entered into a form. In my controller, I'm getting the form data fine, passing it to a validator with some rules which pass fine, but then when I try to create the User, nothing gets added to the database and it redirects to the basic "Whoops, looks like something went wrong." error page instead of the page I'm telling it to.
Here's my controller function:
public function doRegister() {
$rules = array(
'fname'=>'required|alpha|min:2',
'lname'=>'required|alpha|min:2',
'email'=>'required|email|unique:users',
'company'=>'required|alpha|min:2',
'password'=>'required|alpha_num|between:6,12|confirmed',
'password_confirmation'=>'required|alpha_num|between:6,12'
);
$validator = Validator::make(Input::all(), $rules);
if($validator->passes()) {
User::create(array(
'fname' => Input::get('fname'),
'lname' => Input::get('lname'),
'email' => Input::get('email'),
'password' => Hash.make(Input::get('password')),
'company' => Input::get('company'),
'created_at' => date('Y-m-d H:m:s'),
'updated_at' => date('Y-m-d H:m:s')
));
return Redirect::to('login')->with('message', 'Thank you for registering!');
} else {
return Redirect::to('register')
->with('message', 'The following errors occurred')
->withErrors($validator)
->withInput(Input::except('password'));
}
}
Removing the User::create() section, the redirect works perfectly fine. Just to start with I've included all the database fields in the fillable array in my User model. Still doesn't work. Any ideas?
Not the direct answer to your question, but the quickest way for you to find it.
Open app.php
edit the last line seen in this picture from (in your case) false to true:
Once done that, laravel will tell you what the error is.
One error for sure is
'password' => Hash.make(Input::get('password')),
should be with ::
'password' => Hash::make(Input::get('password')),
You don't need this:
'created_at' => date('Y-m-d H:m:s'),
'updated_at' => date('Y-m-d H:m:s')
laravel will do this for you!
If it doesn't work after this, try to run
php artisan dump-autoload
from your terminal to generate an optimized class loader!
I have a very large registration form.
'username_c' => 'required|unique:contacts_cstm',
'password' => 'required|min:6',
'email' => 'required|email',
'password_repeat' => 'required|same:password',
'first_name' => 'required',
'last_name' => 'required',
'rsa' => 'required',
And so on (another 15 fields)...
The problem is if the form is submitted with nothing entered, about 20 different errors are returned (as they should be).
Except, it would be nice if any of the required fields is NOT entered, to spit back one error saying "All fields are required" or something similar.
I've read through Laravel's docs. on this and didn't find anything. Is there any easy way to do this?
Assuming that all of your fields in the $rules array are required, you should be able to do something as simple as an array_filter($required_fields_input), compare the length against that of your $required_rules and redirect back with a single error message/alert.
See code example below. I tried to keep it simple/commented enough...
Not tested at all ... but theoretically! .... ;)
class YourController {
// ...
public function postFormData()
{
$rules = [
// ...
'first_name' => 'required',
'last_name' => 'required',
'rsa' => 'required'
// ...
];
// Assuming all fields in $rules are "required"
$required_fields = array_keys($rules);
$required_fields_input = Input::only($required_fields);
// Clean out all empty/null fields
$input_not_empty = array_filter($required_fields_input);
if (count($input_not_empty) < count($required_fields))
{
$fill_them_all_in_message = "Please fill in all required fields.";
return Redirect::back()->withMessage($fill_them_all_in_message);
}
/**
* All required fields present
* Continue as usual ..
* .. Validate/Respond/etc...
*/
}
//...
}
I think that pretty much covers your main concern of
a.) Avoiding 15 messages that say "XYZ field is required" ....
b.) Still allowing for the rest of the validation/processing to continue as usual.
Hope that helps!