I am trying to create a register form using Laravel.
I created a request \App\Http\Requests\RegisterNewUserRequest. This is the rules() method:
public function rules()
{
return [
'email' => 'required|email|min:6|max:255|unique:members',
'password' => 'required|min:6|max:16|confirmed',
'name' => 'required|min:2|max:255|alpha',
'surname' => 'required|min:2|max:255|alpha',
];
}
This is my Membership Controller
//Route::post('{locale}/create-new-user, 'MemberController#create_new_user');
public function create_new_user($locale, RegisterNewUserRequest $request)
{
$input = $request->all();
$input['ip'] = Request::ip();
Member::create($input);
return redirect("/$locale/create-account");
}
I violate validation rules while entering information. For example, I enter two different passwords, and enter 1 character to the email field. It does not say anything about it. Also It does not save the data into database. The page is redirected to same empty register form again.
I have got a validation summary in my view
...
#foreach($errors->all() as $e)
<li>{{$e}}</li>
#endforeach
...
I trace data posted. It is posted. But something is weird in flow.
EDIT
This happens also in my contact form. If I fill the contact form properly, it sends an e-mail. But if I violate the validation rules, it doesn't say anything about validation and not send e-mail.
This is my Contact page controller
/**
* #param Requests\SendMessageRequest $
*/
public function sendMessage($locale, SendMessageRequest $request)
{
// validation
// $this->validate($request,
// ['name' => 'required|min:3',
// 'email' => 'required|min:5',
// 'subject' => 'required|min:3',
// 'message' => 'required|min:15'
// ]);
$formData = $request->all();
$formData['ip'] = Request::ip();
Mail::send('contact.send', compact('formData'),
function ($message) use ($formData) {
$message->from('frommail#example.com', 'Example')
->bcc(['bccmail#example.com'])
->to('tomail#example.com')
->subject($formData['subject']);
}
);
}
\App\Http\Requests\SendMessageRequest file's rules() method
public function rules()
{
return [
'name' => 'required|min:3',
'email' => 'required|min:5',
'subject' => 'required|min:3',
'message' => 'required|min:15',
];
}
Actually it was working before. After adding multi language feature validation did not worked. I do not know if there is any relation.
I suspect about use statements at the top of controllers and requests.
Related
When validating data with the validator, it's possible to get all processed data from the validator using the getData() method. However, that returns all data that has been passed into the validator. I only want the data that actually fit the validation pattern.
For example:
$data = [
'email' => email#example.com,
'unnecessaryKey' => 'whatever'
];
$validator = Validator::make($data, [
'email' => 'required|string',
]);
$validator->getData()
Would return the "unnecessaryKey" as well as the email. The question is: Is it possible to only return the email in this case, even though i passed in unnecessaryKey as well?
if you are getting the data from the $request you can try
$validator = Validator::make($request->only('email') , [
'email' => 'required|string',
]);
if you are validating a $data array then you can try
$validator = Validator::make(collect($data)->only('email')->toArray() , [
'email' => 'required|string',
]);
Hope this helps.
You should use Form Requests for this.
1) Create a Form Request Class
php artisan make:request StoreBlogPost
2) Add Rules to the Class, created at the app/Http/Requestsdirectory.
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
3) Retrieve the request in your controller, it's already validated.
public function store(StoreBlogPost $request)
{
// The incoming request is valid...
// Retrieve the validated input data...
$validated = $request->validated();
}
Lets say I have the following Custom Request:
class PlanRequest extends FormRequest
{
// ...
public function rules()
{
return
[
'name' => 'required|string|min:3|max:191',
'monthly_fee' => 'required|numeric|min:0',
'transaction_fee' => 'required|numeric|min:0',
'processing_fee' => 'required|numeric|min:0|max:100',
'annual_fee' => 'required|numeric|min:0',
'setup_fee' => 'required|numeric|min:0',
'organization_id' => 'exists:organizations,id',
];
}
}
When I access it from the controller, if I do $request->all(), it gives me ALL the data, including extra garbage data that isn't meant to be passed.
public function store(PlanRequest $request)
{
dd($request->all());
// This returns
[
'name' => 'value',
'monthly_fee' => '1.23',
'transaction_fee' => '1.23',
'processing_fee' => '1.23',
'annual_fee' => '1.23',
'setup_fee' => '1.23',
'organization_id' => null,
'foo' => 'bar', // This is not supposed to show up
];
}
How do I get ONLY the validated data without manually doing $request->only('name','monthly_fee', etc...)?
$request->validated() will return only the validated data.
Example:
public function store(Request $request)
{
$request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
$validatedData = $request->validated();
}
Alternate Solution:
$request->validate([rules...]) returns the only validated data if the validation passes.
Example:
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
}
OK... After I spent the time to type this question out, I figured I'd check the laravel "API" documentation: https://laravel.com/api/5.5/Illuminate/Foundation/Http/FormRequest.html
Looks like I can use $request->validated(). Wish they would say this in the Validation documentation. It makes my controller actions look pretty slick:
public function store(PlanRequest $request)
{
return response()->json(['plan' => Plan::create($request->validated())]);
}
This may be an old thread and some people might have used the Validator class instead of using the validator() helper function for request.
To those who fell under the latter category, you can use the validated() function to retrieve the array of validated values from request.
$validator = Validator::make($req->all(), [
// VALIDATION RULES
], [
// VALIDATION MESSAGE
]);
dd($validator->validated());
This returns an array of all the values that passed the validation.
This only starts appearing in the docs since Laravel 5.6 but it might work up to Laravel 5.2
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'
]);
How can i make a custom validation rule to an input which value must be an integer and starting with 120?
I already read about making custom messages but didnt understand about rules.
I want to use a regex to validate the data. ^120\d{11}$ here is my regex.
I'm new in Laravel that's why cant now imagine how to do that.
A custom validation to use it in $this->validate($request, []);
Now i'm validating data like so:
$this->validate($request, [
'user_id' => 'integer|required',
'buy_date' => 'date',
'guarantee' => 'required|unique:client_devices|number',
'sn_imei' => 'required|unique:client_devices',
'type_id' => 'integer|required',
'brand_id' => 'integer|required',
'model' => 'required'
]);
The input that i want to add custom validation is guarantee
The quickest neatest way is an inline validator in your controller action:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'number' => [
'regex' => '/^120\d{11}$/'
],
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
return view('welcome');
}
Where number is the name of the field being submitted in the request.
If you have a lot of validation to do, you might want to consider using a Form Request instead, as a way of consolidating a lot of validation logic.
You can create custom validations in your controller as:
$name = Input::get('field-name')
$infoValidation = Validator::make(
array( // Input array
'name' => $name,
),
array( // rules array
'name' => array("regex:/^120\d{11}$"),
),
array( // Custom messages array
'name.regex' => 'Your message here',
)
); // End of validation
$error = array();
if ($infoValidation->fails())
{
$errors = $infoValidation->errors()->toArray();
if(count($errors) > 0)
{
if(isset($errors['name'])){
$response['errCode'] = 1;
$response['errMsg'] = $errors['name'][0];
}
}
return response()->json(['errMsg'=>$response['errMsg'],'errCode'=>$response['errCode']]);
}
Hope this helps.
Since Laravel 5.5, you can make the validation directly on the request object.
public function store(Request $request)
{
$request->validate([
'guarantee' => 'regex:/^120\d{11}$/'
]);
}
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' ,
]);
}