only get validated data from laravel validator - php

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();
}

Related

Method Illuminate\Http\Request::validated does not exist

i tried use validation system but give me error Method Illuminate\Http\Request::validated does not exist.
fileController.php
public function store(Request $request)
{
$this->validate($request, [
'titre' => ['bail','required_without:titre', 'string','min:3', 'max:255'],
'name' => ['bail','required_without:name', 'string','min:3', 'max:255'],
]);
$file= new File($request->validated());
$file->save();
return Redirect::to("/")
->withSuccess('Great! file has been successfully uploaded.');
}
There is no validated method on Illuminate\Http\Request. That method is only on FormRequests (because you are not the one who calls the validate method on the FormRequest, it is done for you, and there needs to be a way to get that data).
The validate method you are calling on your controller returns the validated data.
$validated = $this->validate(...):
This is another way from #lagbox's answer, in the Laravel's validation docs you will see this.
$validated = $request->validated();
$validated = $validator->validated();
You can try the approach below.
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
$validated = $validator->validated();
You can Validate $request params by this way:
$request->validate([
"param" => "required|string"
])

Return error response if a body params is not mentionned in the validator

I'm using the Laravel Validator to test my incoming request. So to be sure that the request contains an username and an email, I write something like that:
$validator = Validator::make($request->all(), [
'username' => 'required',
'email' => 'required|email'
]);
if ($validator->fails()) {
return response()->json('error', 400);
};
But if in my request I have an additionnal params like name, the validator will not consider it as an error and will not fail.
Have you an idea how I can make my validator more strict so that the request body match exactly?
Technically it's not a validation fail in the Validator. But you could check if there are extra (unexpected) fields and send a JSON response based on that if you wanted.
Something like this maybe?
$validationRules = [
'username' => 'required',
'email' => 'required|email'
];
$validator = Validator::make($request->all(), $validationRules);
// Check if there are extra (unexpected) fields and fail in that case
$extraFields = $request->except(array_keys($validationRules));
if (count($extraFields) > 0) {
return response()->json('error because there are extra fields', 400);
}
if ($validator->fails()) {
return response()->json('error', 400);
}
return response()->json('ok', 200);
I hope it can help you.
Validation rules can be attached only to properties, so I don't think Laravel's Validator is able to do that. But you still can explicitly forbid certain fields by providing a custom closure rule to them, like this:
$denied = function($attr, $value, $fail) {
$fail("{$attr} is denied.");
};
$validator = Validator::make($request->all(), [
'username' => 'required',
'email' => 'required|email',
'name' => $denied,
'password' => $denied
]);
Otherwise you need to implement custom validation logic, probably utilizing the rule array from your validator as a white list.

Call to a member function fails() on array on laravel

Iam just trying to validate some POST datas.
Route::post('/', function(){
$data = ['url' => request('url')];
$validation = Validator::make($data, ['url' => 'required|url'])->validate();
if($validation->fails())
{
$dd('failed');
}
I don't understand why It doesn't work, can you help me please ?
The error you're getting is due to the return type of ->validate(). This will return an array, so $validation will be an array instead of a Validator instance, and you can't call ->fails() on an array. To solve this, simply omit ->validate():
$validation = Validator::make($data, ['url' => 'required|url']);
if($validation->fails()){
dd("Failed");
}
Sidenote; watch your syntax. $dd() is not a valid call.
You may use the validate method provided by the Illuminate\Http\Request object directly as follow
$request->validate([
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
]);
//if fails code after this line will not be executed
This validation will auto redirected to back.This was default validation by laravel. If it not fails,it will continue with executing.
Manually
Now you can implement manually and redirect as your requirment.
use Validator;
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
//checks your validation and redirect as you want
if ($validator->fails()) {
return redirect('where/ever/you/want')
->withErrors($validator)
->withInput();
}
Again you can default redirection,by calling validate() method
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();
If you call validate method it will redirect as default laravel.
dd() is a method,short version of die and dump
Useful link:
https://github.com/laravel/framework/blob/5.7/src/Illuminate/Validation/Validator.php#L312

validate on array parameter igoners my rules and update

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.3: Form Validation does not show errors

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.

Categories