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

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

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"
])

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

only get validated data from laravel validator

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

Laravel custom validation rule

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}$/'
]);
}

Return JSON Response with form errors in Laravel

So I currently validate my forms by doing:
$this->validate($request, [
'title' => 'required',
'content' => 'required|min:3'
]);
How do I take these validation errors and push them back through JSON? The docs state that $this->validate(...) if false will redirect back and allow you to display errors ...
How do you validate server side for API requests?
You need to use Validator::make and then return response in json with array or your errors.
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Response::json(['errors' => $validator->getMessageBag()->toArray()], 200);
}
Note that you also need to setup $rules variable.
For example:
$rules = ['email' => 'required|email'];
Hope it will help.

Categories