Laravel validation Error messages to string - php

I want to convert laravel validation error array to a comma separated string. This is to use in an api service for an ios application. So that the iOs developer can process error messages easily.
I tried,
$valArr = [];
foreach ($validator->errors() as $key => $value) {
$errStr = $key.' '.$value[0];
array_push($valArr, $errStr);
}
if(!empty($valArr)){
$errStrFinal = implode(',', $valArr);
}
But it is not working.

You should do like this :
$errorString = implode(",",$validator->messages()->all());
P.S. Assuming
$validator = Validator::make($dataToBeChecked,$validationArray,$messageArray)

The $validator->errors() returns a MessageBag,
see: https://laravel.com/api/5.3/Illuminate/Support/MessageBag.html.
You are close, you need to call the getMessages() function on errors(), so:
foreach ($validator->errors()->getMessages() as $key => $value) {
Hope this helps :)

You are not converting validation errors to array.Please use the below function and pass validation errors as parameter.
public function validationErrorsToString($errArray) {
$valArr = array();
foreach ($errArray->toArray() as $key => $value) {
$errStr = $key.' '.$value[0];
array_push($valArr, $errStr);
}
if(!empty($valArr)){
$errStrFinal = implode(',', $valArr);
}
return $errStrFinal;
}
//Function call.
$result = $this->validationErrorsToString($validator->errors());

If you are doing it like me without your validator and you are pulling messages from the exception you can use laravel helper Arr::flatten($array);
Link and code are for laravel 8.x but I tested this with 5.7 ;) It works.
From documentation:
use Illuminate\Support\Arr;
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
$flattened = Arr::flatten($array);
// ['Joe', 'PHP', 'Ruby']
My code:
try {
$request->validate([
'test1' => 'required|integer',
'test2' => 'required|integer',
'test3' => 'required|string',
]);
} catch (ValidationException $validationException) {
return response()->json([
'type' => 'error',
'title' => $validationException->getMessage(),
'messages' => Arr::flatten($validationException->errors())
], $validationException->status);
} catch (\Exception $exception) {
return response()->json([
'type' => 'error',
'title' => $exception->getMessage(),
], $exception->getCode());
}
As you can see I am pulling the message and setting it as my title. Then I am using Arr::flatten($validationException->errors()) to get the validation messages and but to flatten my array for SweetAlert2 on the frontend.
I know I am late but I hope it will help someone that comes across these problems.
Greetings! :)

Related

Laravel API Validation errors to be displayed

I am valdating the fields sent through api and need to display the errors.
I tried using try and catch no errors thrown. I have already have a code validating the login
try {
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean',
]);
} catch (Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
I found no errors return has json instead it is redirecting to the login page
How to handle rerros in API and sent the message as json?None of the example show the way to handle errors. I tried with everything
And also how to handle errors while creating the model
try {
$company = Company::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'country_code' => $data['country_code']]);
} catch (Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
$request->validate() should automatically return a response to the browser with errors if it fails, it doesn't throw an exception.
If your request is json it should detect that and return the error in a json error response, you can catch this in your front-end javascript and interrogate the response to interpret the error message.
e.g. using axios:
this.$axios.post('your api url',{data})
.then(response=>{
// ALL Good
})
.error(error=>{
// Catch returned error and process as required
});
If as you say I found no errors return has json instead it is redirecting to the login page this probably means that Laravel thinks that the request is a standard request, in which case it will issue a response()->back()->withErrors() which is probably what's sending it back to your login.
Try checking the original request type and ensure it's json, it should have a header of Accept: application/json.
Alternatively you can define your own validator
https://laravel.com/docs/7.x/validation#manually-creating-validators, and process the validation on the server as you like.
If there is error into validation then it will automatilly handle by laravel. You don't need to catch exception for that. It doesn't through exception.
Look it sample function which I have used for store Region
public function createRegion(Request $request)
{
$data = $request->all();
// Create a new validator instance.
$request->validate([
'name' => 'required',
'details' => 'required'
]);
try {
$region = new Region();
$region->name = $data['name'];
$region->details = $data['details'];
$region->save();
$content = array(
'success' => true,
'data' => $region,
'message' => trans('messages.region_added')
);
return response($content)->setStatusCode(200);
} catch (\Exception $e) {
$content = array(
'success' => false,
'data' => 'something went wrong.',
'message' => 'There was an error while processing your request: ' .
$e->getMessage()
);
return response($content)->setStatusCode(500);
}
}

I cannot print the array that I am sending to the database - Laravel

I have the following function, but when I run it in Postman to see the result, it doesn't print any value to me, it doesn't even give me an error. The var_dump set if it detects them, but the array does not... I think there is something wrong in the method updateOrCreate , because when I print this variable with var_dump, I can't see anything in the console.
This is the function:
public function createBidRival(Request $request)
{
$response = array('code' => 400, 'error_msg' => []);
if (!$request->id_karatekas) array_push($response['error_msg'], 'id_karateka is required');
if (!$request->id_participant_bid_send ) array_push($response['error_msg'], 'id_participant_bid_send is required');
if (!$request->id_participant_bid_receive) array_push($response['error_msg'], ' id_participant_bid_receive is required');
if (!$request->bid_rival) array_push($response['error_msg'], 'bid rival is required');
if (!count($response['error_msg']) > 0) {
try {
var_dump($request->id_karatekas);
var_dump($request->id_participant_bid_send);
var_dump($request->id_participant_bid_receive);
var_dump($request->bid_rival);
$bidRival = new BidBetweenRivals();
$bidRival = BidBetweenRivals::updateOrCreate(
[
'id_participant_bid_send' => $request->id_participant_bid_send,
'id_participant_bid_receive' => $request->id_participant_bid_receive,
'id_karatekas' => $request->id_karatekas
],
[
'id_participant_bid_send' => $request->id_participant_bid_send,
'id_participant_bid_receive' => $request->id_participant_bid_receive,
'id_karatekas' => $request->id_karatekas,
'bid_rival' => $request->bid_rival
]
);
$bidBetweenRivals->save;
$response = array('code' => 200, 'bidBetweenRivals' => $bidRival, 'msg' => 'Bid created');
}catch(\Exception $exception) {
$response = array('code' => 500, 'error_msg' => $exception->getMessage());
}
}
}
Dump to see whether if (!count($response['error_msg']) > 0) true or not and also dump something in the catch block to see if exception is occurring or not.
You can also test by commenting out the updateOrCreate part to see if it is interfering.

Lumen doesn't return data when of all countries

Am trying to get list of all countries in lumen api but when i return all the data like this
echo json_encode([
'success' => true,
'data' => $results
]);
or
return json_encode([
'success' => true,
'data' => $results
]);
or
return response([
'success' => true,
'data' => $results
]);
i just get nothing no data no error
i only get data when i limit(15)
here is my function to get the list of countries
$output = [];
$database = \DB::table('country_t')
->select(['nameX3'])->get();
foreach ($database as $item) {
$name = $item->nameX3;
$toLowerCase = strtolower(trim($name));
$urlName = str_replace(' ', '-', $toLowerCase);
$output[] = [
'name' => $item->nameX3,
'url' => $urlName . '-simcards',
];
}
return response([
'success' => true,
'data' => $output
]);
So this function does not return anything except when i dd($output); or limit(15)
Please help
Thanks in advance.
Thanks to #porloscerros Ψ comment, I was able to get an error at least.
After I used return response()->json(['success' => true, 'data' => $output]); I got an error saying Malformed UTF-8 characters, possibly incorrectly encoded.
Issue is the data that is being encoded by json_encode contains even non-utf8 characters such as Russian words, etc.
To solve this issue I created a function that will encode this data using mb_convert_encoding, so I also had to make it handle even multidimensional array
function toUTF8( $mixed ) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = toUTF8($value);
}
} elseif (is_string($mixed)) {
return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
}
return $mixed;
}
Then calling the function
$this->toUTF8($output);
All in all if you have data that contains non-utf8 characters, you must encode the data.

unmarshalItem DynamoDB & PHP not working

I wanted to unmarshal the dynamodb scan query response and here is my code
$client = $this->getClient();
$result = $client->scan([
'ExpressionAttributeValues' => [
':v1' => [
'S' => "200",
],
],
'FilterExpression' => 'id = :v1',
'ProjectionExpression' => "entryStamp",
'TableName' => $this->table,
]);
return $this->unmarshalItem($result['Items']);
It returns error "Unexpected type: entryStamp."
I was searching for this myself and it doesn't seem possible at the moment.
I didn't find anything specifically about PHP but this thread describe the exact same problem with GO.
So the best way to go about it is to do what Saurabh advised in his comment:
$result = $this->client->query($params);
$data = [];
foreach( $result['Items'] as $item)
{
$data[] = $marshaler->unmarshalItem($item);
}
return $data;

Create a filter using Gmail API

Google released recently a new version of its Gmail API which now makes possible to create filters.
However the documentation is quite limited and I'm facing issues to get it working. I'm using the latest version of their PHP client. Any help would be appreciated to construct the request body.
public $gmail;
public function createFilter($userId) {
try {
$filter = new Google_Service_Gmail_Resource_UsersSettingsFilters();
// Here, we should create the request body...
// https://developers.google.com/gmail/api/v1/reference/users/settings/filters#resource
// $filter->setCriteria() ??
$this->gmail->users_settings_filters->create($userId, $filter);
} catch (Exception $e) {
// Logging errors...
}
}
UPDATE (Working method)
public $gmail;
public function createFilter($userId) {
try {
$filter = new Google_Service_Gmail_Filter([
'criteria' => [
'from' => 'example#gmail.com'
],
'action' => [
'addLabelIds' => ['STARRED']
]
]);
$this->gmail->users_settings_filters->create($userId, $filter);
} catch (Exception $e) {
// Logging errors...
}
}
See https://github.com/google/google-api-php-client#making-requests for guidance on constructing request objects. You should be able to populate the filter properties using native PHP arrays or the autogenerated objects. Example:
$filter = new Google_Service_Gmail_Resource_UsersSettingsFilters([
'criteria' => [
'from' => 'somebody#example.com'
],
'action' => [
'addLabelIds' => ['STARRED']
]
]);

Categories