Laravel API Validation errors to be displayed - php

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

Related

GuzzleHttp\Exception\ConnectException: cURL error 7: Failed to connect - Laravel

I'm trying to post a Third party Api with raw body with my controller , It works fine when I test it from localhost , but when I publish my project on the Server (Cpanel) , I get this Error :
GuzzleHttp\Exception\ConnectException: cURL error 7: Failed to connect.
Here is an example of my code inside the controller :
use Illuminate\Support\Facades\Http;
public function testApi(){
$array = [
'FullName' => 'Full Name',
'PhoneNumber' => '9999999999',
'Date' => '2022-06-26 17:20',
'Note' => '',
];
try {
$response = Http::withBody(json_encode($array) , 'application/json')
->post('https://example');
return $response->status();
} catch (Exception $exception){
return $exception;
}
}
and I also tried using GuzzleHttp and the same thing it works on localhost , and not working when I publish the project on the server.
use GuzzleHttp\Client;
public function testApi(){
$array = [
'FullName' => 'Full Name',
'PhoneNumber' => '9999999999',
'Date' => '2022-06-26 17:20',
'Note' => '',
];
try {
$client = new Client();
$response = $client->request('POST', 'https://example', [
'body' => json_encode($array),
'headers' => [
'Content-Type' => 'application/json',
]
]);
return $response->getStatusCode();
} catch (Exception $exception){
return $exception;
}
}
before disable firewall and test again.
there can be a firewall that blocks your requests

how to work with laravel transaction rollback

I am trying to execute some queries which are dependant on each other, so what I want is if any error occurs then rollback all the queries inside transaction. what I've tried so far is
DB::transaction(function () use($user,$token,$request) {
$billing = User_billings::create([
'users_id' => $user->id,
'agent_id' => null,
'purpose' => 'Some Purpose',
'agent_token_id'=>$token->id,
'amount' => $request->amount,
'payment_method' => 'Agent Token',
'status' => 1
]);
if($billing){
$user_jorunal = User_journal::create([
'bill2_id' => $billing->id, //Intentionally made this error to test transaction, this should be 'bill_id'
'u_id' => $user->id,
'purpose' => 'Topup via Agent Token',
'debit' => $billing->amount,
'invoice_number' => time()
]);
if($user_jorunal){
if($this->agentTokenBalance($request->token_id) == 0){
$token->status=1;
$token->update();
}
return response()->json(['status'=>true,'message'=>'TopUp was Successful!']);
}
}
});
so when I execute this query It generates an error as SQLSTATE[HY000]: General error: 1364 Field 'bill_id' doesn't have a default value, but it also creates a row on user_billings table.
Can you please specify where I am wrong?
all of the above code is running fine, be sure that there is no logical error in query except the intentional one .
I am using laravel 5.7 in this project
PHP version is 7.2.19
following laravel documentation
Manually Using Transactions
use DB::beginTransaction(); to start transaction.
use DB::rollBack(); after each error.
use DB::commit(); when transaction confirmed. ;
laravel reference
Create a $status variable that will make sure that everything has been creeted in db. If any error occur, all db action will be rolled back.
Below, i have adapted your code with that logic.
$status = true;
try
{
DB::beginTransaction();
$billing = User_billings::create([
'users_id' => $user->id,
'agent_id' => null,
'purpose' => 'Some Purpose',
'agent_token_id' => $token->id,
'amount' => $request->amount,
'payment_method' => 'Agent Token',
'status' => 1,
]);
$user_jorunal = User_journal::create([
'bill2_id' => $billing->id, //Intentionally made this error to test transaction, this should be 'bill_id'
'u_id' => $user->id,
'purpose' => 'Topup via Agent Token',
'debit' => $billing->amount,
'invoice_number' => time(),
]);
$status = $status && $billing && $user_jorunal;
} catch (\Exception $e)
{
DB::rollBack();
//throw $e; //sometime you want to rollback AND throw the exception
}
//if previous DB action are OK
if ($status)
{
DB::commit();
if ($this->agentTokenBalance($request->token_id) == 0)
{
$token->status = 1;
$token->update();
}
return response()->json(['status' => true, 'message' => 'TopUp was Successful!']);
} else
{
DB::rollBack();
//return somme errors
}
Please note that MyIsam engine doesn't support transaction as explained here MyIsam engine transaction support.
Haven't used the DB::transaction with a callback method... but you can do the following
DB::beginTransaction();
$billing = new User_billings;
$billing->users_id = $user->id;
// rest of the assignments
$billing->save();
// Rest of your code... Inserts, Deletes, Updates...
DB::commit();
You don't need to implement the DB::rollBack() in this case, if anything fails between those two lines, the transaction won't commit.

Laravel DB::select is breaking a future transaction

I have the following code :
DB::select($sql, $params);
DB::beginTransaction();
try {
DB::commit();
} catch (Exception $e) {
DB::rollback();
return [
'code' => 500,
'error' => true,
'message' => 'There was a problem saving your transaction.'
];
}
Which is causing the following error:
message: "There is no active transaction"
exception "PDOException"
There should be more instructions in the try statement but to show that none of them have an affect they have been removed. It seems to be that select is for some reason opening a transaction and not closing it. (The select is running an SP that returns two result sets but I only want one hence the use of select.) Everything works well without the select statement, and the select statement on it's own doesn't cause any errors and returns what I need. However, if I put the select statement in the try statement it causes an exception.
Thanks.
Does something like this work?
DB::beginTransaction();
DB::select($sql, $params);
try {
// your code that could fail
}
catch (Exception $e)
{
DB::rollback();
return [
'code' => 500,
'error' => true,
'message' => 'There was a problem saving your transaction.'
];
}
DB::commit();
return [
'code' => 200,
'error' => false,
'message' => 'Successful transaction.'
];

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.

new (Json)Response shows blank page (Symfony HttpFoundation)

I am using the HttpFoundation in my small project: use \Symfony\Component\HttpFoundation\JsonResponse as JsonResponse;
Unfortunately all my responses (tried JsonResponse, Response and BinaryFileResponse) only return a blank page, no errors and the code gets executed normally, e.g.
/* Get Inputs */
if (!$data = filter_input(INPUT_GET, 'url', FILTER_VALIDATE_URL)) {
return new JsonResponse(array(
'result' => 'error',
'message' => 'URL is invalid or missing'
));
}else{
return new JsonResponse(array(
'result' => 'success',
'message' => 'FINE'
));
There are no errors in the logs either.
Any ideas how to approach the issue?
//UPDATE FOR CLARIFICATION
$json = new JsonResponse(array(
'result' => 'error',
'message' => 'Encrypt is invalid or missing'
));
echo $json;
returns HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json {"result":"error","message":"Encrypt is invalid or missing"}
but why does the return not work?
You're not using the full stack framework, so you need to be sure that your front controller or equivalent calls $response->send(); to deliver the response to the client.
It's addition to answer:
$response = new JsonResponse(array(
'result' => 'error',
'message' => 'Encrypt is invalid or missing'
));
$response->send();

Categories