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"
])
Related
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
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()];
}
for some reason that I do not know, when I try to pass a validation without request and try to use one if
public function save(Request $request){
$request = $request->validate([
'name' => ['string', 'max:255'],
'email' => ['string', 'email', 'max:255', 'unique:users'],
]);
if($request->name != null){
return $request;
}
return $request;
}
You are replacing the type of your $request with the result from validate()
The validation will handle the what you wish to, so no need to worry. If you say the variable name is required, it will enforce it to not be null or empty;
So, just replace the result to a specific variable instead of replacing $request by doing:
$validationResult = $request->validate([
'name' => ['string', 'required', 'max:255'],
'email' => ['string', 'required', 'email', 'max:255', 'unique:users'],
]);
Better option than this is to create a specific request type by running
php artisan make:request YourRequest`
Your new class will be ready at app/Http/Requests where you can specify not only your rules() as you have in your array, as the messages() you wish each to output.
Then all you need to do is to replace your save(Request $request)
for save(YourRequest $request) which will kick in the validation before it triggers the method, which means you are at ease within the controller method to do the logic instead of having to double check your variables
Examples for common rules() within your class, will be:
public function rules()
{
return [
'email' => 'required|email|unique:users|max:255',
'name' => 'required|min:2|max:200',
];
}
public function messages()
{
return [
'email.required' => 'The email field is required',
'email.email' => 'The email field needs to be an email type. Ex:. type#gmail.com',
....
];
}
Obviously adjust the rules and messages to your project and liking :)
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