Help plz. "How add error user mistake in laravel" I want show JSON file - error $regex - reqular rules
I need get mistake on not correct sourceUrl
$this->validate($request,[
'title' => 'required|min:10|max:250', //work
'subTitle' =>'sometimes|present|nullable|min:10|max:250', //work
'message' => 'required|min:10',//work
'recommendPic' => 'present|nullable', //work
'pic' => 'required|sometimes', //file - check upload file,image need fix
'sourceUrl' =>'required|regex:'.$regex,
],[
'sourceUrl.regex:'.$regex=>'mistake',
]);
You need to return your failed validation messages, something like the following:
$validation = Validator::make($request->all(), [
'title' => 'required|min:10|max:250', //work
'subTitle' =>'sometimes|present|nullable|min:10|max:250', //work
'message' => 'required|min:10',//work
'recommendPic' => 'present|nullable', //work
'pic' => 'required|sometimes', //file - check upload file,image need fix
'sourceUrl' =>'required|regex:'.$regex,
]);
// if validation fails
if ($validation->fails()) {
return response()->json([
'status' => 'failure',
'errors' => $validation->errors()
], 400);
}
// validation passes
return response()->json(['status' => 'success'], 200);
'sourceUrl.regex:'.$regex=>'mistake', is not valid PHP code.
It should be something like: 'sourceUrl.regex' => 'regex mistake'
This redirects back with the error message regex mistake.
In your view you can print the message with #error('sourceUrl') {{ $message }}#enderror.
Related
I write validation for email in my controller
public function store(Request $request)
{
/*
* validate request
*/
$request->validate([
'email' => ['required', 'unique:leads', 'email'],
]);
return response()->json([],422);
if (\App\Models\Lead::where(['email' => $request->get('email')])->count() > 0) {
// user found
return response()->json([ 'data' => [
'message' => 'lindirizzo email è già registrato'
]], 200);
}
else {
// Register the new user or whatever.
$client = \App\Models\Lead::create(['email' => $request->get('email'),]);
return response()->json([ 'data' => [
'message' => 'Registrato con successo!'
]], 201);
}
}
And when i write the same email in front i get error POST http://127.0.0.1:8000/api/register/leads 422 (Unprocessable Content)
My network respons its ok,
{"message":"validation.unique","errors":{"email":["validation.unique"]}}
But i dont want to show error in console
This line of code is unnecessary.
// ...
return response()->json([],422);
// ...
Remove it.
Writing The Validation Logic
... if the validation fails, the proper response will automatically be
generated. If the validation passes, our controller will continue
executing normally.
Addendum
The block of code below is unnecessary as well since the validation rule 'unique:leads' is sufficient:
// ...
if (\App\Models\Lead::where(['email' => $request->get('email')])->count() > 0) {
// user found
return response()->json([ 'data' => [
'message' => 'lindirizzo email è già registrato'
]], 200);
}
// ...
Remove it as well!
If you wish to have a custom message for the "unique email" validation, add it as the second parameter of the ->validate(...) method:
$request->validate([
'email' => ['required', 'unique:leads', 'email'],
], [
'email.unique' => 'lindirizzo email è già registrato'
]);
First, you need to check is there any email is available already or not in the table.
If you found any count of that email then simply ignore creating a record else you can add that email with a new entry inside the database.
if (Lead::where(['email' => $request->get('email')])->count() > 0) {
return response()->json([ 'data' => [
'message' => 'User data get successfully'
]], 200);
}else{
// Add a user with new email and send json response
}
}
I'm having some problems with validations in my api.
I need to send a json array like this:
[
{
"acktime": "2021-09-25 08:45:07",
"temp": 15.6
},
{
"acktime": "2021-09-25 08:45:07",
"temp": 15.6
}
probably more array....
]
I would like to vaidate one by one array and store only the valid data returning error for unvalid data, I have tried a foreach cylce but it convert the array to object but the validate::make want only array.
I have tried this:
$validator = Validator::make($request->all(), [
'*.acktime' => 'required',
'*.temp' => 'required|numeric'
]);
$validatedData = $validator->validated();
var_dump($validatedData);
return response()->json($validatedData);
But If I send wrong data I get only error without having valid data, so I've tried this way:
foreach($datas as $data){
$arr = (array)$data;
$validator = Validator::make($arr, [
'acktime' => 'required',
'temp' => 'required|numeric'
]);
if ($validator->fails()) {
continue;
} else {
$newrawData = new rawData([
'acktime' => $data->acktime,
'temp' => $data->temp,
'synctime' => now()
]);
$newrawData->save();
}
}
return response('OK', 200); //or error if some data are not ok
}
In this way it work, bot I have no idea about get, a probable, validation error..(for the moment there's a continue for continue the cycle) any suggestion?
There are two ways for approaching this kind of validation:
make a custom rule in laravel validation from below and put your validation code in it and this will work:
https://laravel.com/docs/8.x/validation#custom-validation-rules
easier way:
$data = [ 'data' => $requests->all() ];
$validator = Validator::make($data, [
'data.*.name' => 'required|string',
'data.*.' => 'required|string'
]);
Facing cURL Error: Operation timed out after 15001 milliseconds with 0 bytes received issues with Woocomerce API to create products.
I am using the Laravel package i.e https://github.com/Codexshaper/laravel-woocommerce
It was working fine and creating products but suddenly it stopped working and start throwing PHP errors.
Below are the method that I am using to create a book on Woocomerce from laravel Controller:
public function addProductToWC(Request $request)
{
set_time_limit(0);
$response = '';
if ($request->isMethod('post')){
if(!empty($request->get('book_id'))){
$book = Book::find($request->get('book_id'));
$coverImgPath = base_path('public/customize_book/'.Session::get('cover_image'));
if (file_exists($coverImgPath)) {
$imageurl = url('/public/customize_book/'.Session::get('cover_image'));
} else {
$imageurl = url('/images/'.$book->bookimage);
}
if(!empty($book->id)){
$data = [
'name' => $book->title,
'type' => 'simple',
'regular_price' => number_format($request->get('book_price')),
'description' => (!empty($book->description) ? $book->description :''),
'short_description' => 'Simple product short description.',
'categories' => [
[
'id' => 1
]
],
'images' => [
[
'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg'
],
[
'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg'
]
]
];
$product = Product::create($data);
if($product['id']){
$response = array('error' => false,'code' => '200', 'data' => array('product_id' => $product['id'], 'message' => 'Product created successfully.'));
}else{
$response = array('error' => true,'code' => '401', 'data' => array('product_id' => $product['id'], 'message' => 'Product syncing failed please try again later.'));
}
}else{
$response = array('error' => true,'code' => '401','message' => 'Invalid book detail please try again.');
}
}else{
$response = array('error' => true,'code' => '401','message' => 'Invalid book detail please try again.');
}
}else{
$response = array('error' => true,'code' => '401','message' => 'Invalid method please try again.');
}
// return response
return response()->json($response);
}
Looking at the composer.json at https://github.com/Codexshaper/laravel-woocommerce/blob/master/composer.json, I can see that they are using the woocommerce client "automattic/woocommerce": "^3.0" This defaults to a request timeout of 15 seconds, hence why set_time_limit(0); didn't fix the issue.
When using it directly you'd set the timeout in the options
$woocommerce = new Client(
env('MGF_WOOCOMMERCE_API_URL'), // Your store URL
env('MGF_WOOCOMMERCE_API_KEY'), // Your consumer key
env('MGF_WOOCOMMERCE_API_SECRET'), // Your consumer secret
[
'timeout' => 120, // SET TIMOUT HERE
'wp_api' => true, // Enable the WP REST API integration
'version' => 'wc/v3' // WooCommerce WP REST API version
]
);
Looking at the library source https://github.com/Codexshaper/laravel-woocommerce/blob/master/src/WooCommerceApi.php
$this->client = new Client(
config('woocommerce.store_url'),
config('woocommerce.consumer_key'),
config('woocommerce.consumer_secret'),
[
'version' => 'wc/'.config('woocommerce.api_version'),
'wp_api' => config('woocommerce.wp_api_integration'),
'verify_ssl' => config('woocommerce.verify_ssl'),
'query_string_auth' => config('woocommerce.query_string_auth'),
'timeout' => config('woocommerce.timeout'),
]
);
It looks like the timeout is coming from woocommerce.timeout in your Laravel config file.
I have set up a notification with action buttons, but I do not receive the in interactive payload. I have configured the webhook URL here:
When I post to that URL in Postman everything is fine. But when I press the buttons I get no callback to that URL I get nothing(I'm logging all requests to that URL). I also get a warning triangle next to my buttons like this:
I get no other feedback and no Ideas where I should debug.
The massage with the buttons is published with Laravel's Slack notification channel plus this package for block support: https://github.com/nathanheffley/laravel-slack-blocks
This is the code for sending the notification, but I don't think it is relevant:
public function toSlack()
{
$model = $this->model;
$message = (new SlackMessage())
->error()
->content('New report!');
$message->attachment(function ($attachment) use ($model) {
$attachment->block(function ($block) {
$block
->type('actions')
->elements([
[
'type' => 'button',
'text' => [
'type' => 'plain_text',
'text' => 'Approve',
'emoji' => false,
],
'value' => 'click_me_123',
'action_id' => 'approve_x',
'style' => 'primary',
],
[
'type' => 'button',
'text' => [
'type' => 'plain_text',
'text' => 'Reject',
'emoji' => false,
],
'value' => 'click_me_1234',
'action_id' => 'reject_x',
'style' => 'danger',
],
]);
});
});
return $message;
}
Any ideas how I should proceed with debugging?
Today, I noticed that I got some more information if I hoovered the triangle, but I'm pretty sure that didn't work yesterday. I got the message "500 server error" there.
The problem was that the payload JOSN is sent as a form-data field and not in the POST request body like normal. Why do they send the payload like this? It makes no sense.
I wonder what I've made wrong, I want to save in db some values whats not come form POST or GET:
public function saveAction()
{
$wikiTable = $this->getServiceLocator()->get('WikiTable');
$data = array('source' => $someVal);
$form = new WikiForm();
$inputFilter = new \MyApp\Form\WikiFilter();
$form->setInputFilter($inputFilter);
$form->setData($data);
$this->saveWiki($form->getData());
//$this->saveWiki($data);
}
WikiFilter:
$this->add(
array(
'name' => 'source',
'required' => false,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
)
)
);
And Form:
$this->add(array(
'name' => 'source',
'type' => 'Zend\Form\Element\Hidden',
'options' => array(
'label' => 'source',
)
));
In response I recive error:
Zend\Form\Form::getData cannot return data as validation has not yet
occurred
After this line:
$form->setData($data);
You need to put the rest of your code into something like this:
if($form->isValid()){
$this->saveWiki($form->getData());
}
Otherwise your form isn't validated and you won't get any data back from it by calling $form->getData()
So whenever you work with a form (not matter if the data come from a POST request or not) make sure to call the function isValid() on the form variable because otherwise you won't get the data back and you will get the error you wrote before