response error REST API CI3 not display in Client - php

I'm having a problem getting errors from the Rest API I created with codeigniter 3, or rather using the library from "https://github.com/chriskacerguis/codeigniter-restserver".
This problem occurs when I POST data to server via API.
When I try to post the same data as the data in the database. it will issue an error message data already exists. with status 409.
but I didn't get the error in the client application that I made. only displays "Null"
https://localhost/server/api/room
public function index_post()
{
try {
$input = json_decode(file_get_contents('php://input'), true);
if (empty($input['noroom'])) {
throw new Exception('Error: field not found, field must be named noroom');
return false;
}
$exists = $this->Roommodel->findRoomByNoroomAndHotel($input['noroom'], $input['hotel_code'])->num_rows();
if ($exists > 0) {
$message = [
'status' => 409,
'message' => 'Data already exists',
];
$this->response($message, REST_Controller::HTTP_CONFLICT);
} else {
$dataRoom = [
'hotel_code' => $input['hotel_code'],
'noroom' => $input['noroom'],
'room_type' => $input['room_type'],
'room_area' => $input['room_area'],
'description' => $input['description'],
];
$insert = $this->Roommodel->save($dataRoom);
if ($insert) {
$data = [
'hotel_code' => $input['hotel_code'],
'noroom' => $input['noroom'],
'room_type' => $input['room_type'],
'room_area' => $input['room_area'],
'description' => $input['description'],
'message' => 'Success created data'
];
$message = [
'status' => 200,
'message' => 'Success',
'data' => $data,
];
$this->response($message, REST_Controller::HTTP_OK);
} else {
$message = [
'status' => 400,
'message' => 'Bad Request'
];
$this->response($message, REST_Controller::HTTP_BAD_REQUEST);
}
}
} catch (Exception $e) {
$message = [
'status' => 500,
'message' => $e->getMessage()
];
$this->response($message, REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
}
}
below is my coding on the client side, and I try to do var_dum() the result is "Null" when there is an error.
when I tried insomia, I got the error message.
var $API = "";
function __construct()
{
parent::__construct();
$this->API = "http://localhost/server";
$this->load->library('session');
$this->load->library('curl');
$this->load->helper('form');
$this->load->helper('url');
}
public function create()
{
if ($this->input->is_ajax_request()) {
$data = [
'hotel_code' => $this->input->post('hotel_code'),
'noroom' => $this->input->post('noroom'),
'room_type' => $this->input->post('room_type'),
'room_area' => $this->input->post('room_area'),
'description' => $this->input->post('description'),
];
$response = json_decode($this->curl->simple_post($this->API . '/api/room', json_encode($data), array(CURLOPT_BUFFERSIZE => 10)), true);
var_dump($response); die();
echo json_encode($response);
} else {
show_404();
}
}
if the post data is successful, it will send the success message. and managed to get the message.
please help me to solve this problem

Related

how to redirect to post page when payment is done in laravel

how can i send back to payment page which is post type
My routes
Route::post('/payment', 'PaymentsController#getPayment')->name('/payment');
Route::post('/charge', 'PaymentsController#payPayment');
My controller
first method for post requests
public function getPayment(Request $req)
{
$csdetails = array(['courseid' => $req['courseid'] , 'coursename' => $req['coursename'], 'courseprice' => $req['courseprice']]);
//dd($csdetails);
return view('/payment')->with('csdetails', $csdetails);
}
second method after select to purchase
public function payPayment(Request $request)
{
$price=$request->courseprice;
$this->validate($request, [
'card_no' => 'required',
'expiry_month' => 'required',
'expiry_year' => 'required',
'cvv' => 'required',
]);
//$stripe = Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$stripe = Stripe\Stripe::setApiKey('sk_test_bCgnRBd3BoVvH6QU3gBPbBkQ');
try {
$response = \Stripe\Token::create(array(
"card" => array(
"number" => $request->input('card_no'),
"exp_month" => $request->input('expiry_month'),
"exp_year" => $request->input('expiry_year'),
"cvc" => $request->input('cvv')
)));
if (!isset($response['id'])) {
return redirect()->route('payment');
}
$charge = \Stripe\Charge::create([
'card' => $response['id'],
'currency' => 'USD',
'amount' => $price,
'description' => 'wallet',
]);
if($charge['status'] == 'succeeded') {
here iam getting error of get method because it is getting post type data on payment page
return redirect('payment')->with('success', 'You Purchased A Courses Successfully!');
} else {
return redirect('payment')->with('error', 'something went to wrong.');
}
}
catch (Exception $e) {
return $e->getMessage();
}
}
}
Please help me how to i redirect to payment page whic is post type and save the values in db here

How to upload image using Codeigniter Rest API?

I was read some answer in stackoverflow about this question, but I still not understand because the answer hasn't specified and make me confuse. I have some code below.
I use REST from https://github.com/chriskacerguis/codeigniter-restserver/
My Model API
public function upload(){
$config['upload_path']='./images/';
$config['allowed_types']='jpg|png|jpeg';
$config['max_size']='2048';
$config['remove_space']=TRUE;
$config['overwrite']=TRUE;
$this->load->library('upload',$config);
if ($this->upload->do_upload('id_image')) {
$return = array(
'result'=>'success',
'file'=> $this->upload->data(),
'error'=>'');
return $return;
} else {
$return = array(
'result'=>'failed',
'file'=>'',
'error'=> $this->upload->display_errors());
return $return;
}
}
public function createMember($upload){
$data_member = [
"id_card" => $this->input->post('id_card', true),
"name" => $this->input->post('name', true),
"email" => $this->input->post('email', true),
"id_image" => $upload['file']['file_name']
];
$this->db->insert('member', $data_member);
}
My Controller API
public function index_post(){
$upload = $this->Member_model_api->upload();
if ($this->Member_model_api->createMember($upload) > 0) {
$this->response([
'status' => true,
'message' => 'Member Data was Added'
], REST_Controller::HTTP_CREATED);
} else {
...
REST_Controller::HTTP_BAD_REQUEST);
}
}
Output from Postman
Message: Call to undefined method Member_model_api::upload()
Filename: C:\xampp\htdocs\org\application\controllers\api_controller\Org_member.php
I hope the other developers give me some reference like my code above, thank you very much.

Insert into table is not working inside foreach Laravel 5.8

I amtrying to insert values to laravel table inside a foreach. In my view I am selecting some checkboxes and I need its value to get inserted into a table. In my controller, I am getting all the required values to be inserted into the table. But everytime when I run, the code inside the foreach results in error.
Here is my controller code.
try {
$e_id = request()->segment(3);
$et = $repository->find($e_id);
if (!empty($et)) {
$rules = [
's_users' => 'bail|required|array',
'e_id' => 'bail|required',
];
$messages = [
's_users.required' => required,
'e_id.required' => required ,
's_users.array' => required,
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return response()->json(['error' => 1, 'code' => 422, 'errors' => $validator->errors()], 422);
} else {
DB::transaction(function () use ($request, $admin) {
DB::table('e_users')->whereIn('user_id', $request->input('s_users'))->delete();
foreach ($request->input('s_users') as $suser) {
$eUsers = new EUsers();
$eUsers->e_id = $request->input('e_id');
$eUsers->uid = $suser;
$eUsers->save();
}
});
return response()->json(['error' => 0, 'code' => 200, 'message' => "success"], 200);
}
} else {
throw new \Exception("invalid);
}
} catch (\Exception $e) {
return response()->json(['error' => 1, 'code' => 200, 'message' => "unknown error occurred"], 200);
}
The above code always throws exception, which shows unknown error occured. Thanks in advance

I just want to return JSON error response when ever the token field is missing in headers in codeigniter

Just simply want whenever my Api is called if token is missing it should return a json response that "Token is required"
i'm getting the token in headers
let me explain it with sample code:
$headers = apache_request_headers();
$token = $headers['User-Token'];
if(isset($token)){
$user_details = $this->user_basic_model->get_user_by_token($token);
if (!empty($user_details))
{
$data = $this->fare_model->get_all_fare();
if (empty($data)) {
$arr = array('msg' => 'Error!', 'status_code' => 404);
echo json_encode($arr);
}
else {
$success_array = array('msg' => 'Success!', 'status_code' => 200);
echo json_encode(array_merge($data, $success_array));
}
}
else
{
$arr = array('success' => 'false', 'msg' => 'Unauthorize Request',
'status_code' => 401);
echo json_encode($arr);
}
}
else
{
$arr = array('success' => 'false', 'msg' => 'Token is required',
'status_code' => 401);
echo json_encode($arr);
}
in this case when i don't send User-Token field in headers using postman i got the response properly but with that response i'm getting an error of undefined index "User-token"
i don't want this error to be shown
just modify your code little bit.
if (isset($headers['User-Token'])) {
$token = $headers['User-Token'];
if (empty($token)) {
//your code
} else {
$arr = array('success' => 'false', 'msg' => 'Token is required',
'status_code' => 401);
echo json_encode($arr);
exit();
}
} else {
$arr = array('success' => 'false', 'msg' => 'Token is required',
'status_code' => 401);
echo json_encode($arr);
exit();
}

Object of class Illuminate\Validation\Rules\Unique could not be converted to int

I'm trying to use ignore method in laravel to apply validation on updating profile I have use ignore() for this but looks like I have gone somewhere wrong and ended up with this error can you help me out to find this here is my code. Thanks for your insights :)
User Controller
public function editProfile(Request $request) {
$userId=$request->userId;
$phoneNumber=$request->phoneNumber;
if(!$request){
$this->setMeta("422", "Nothing is there for update");
return response()->json($this->setResponse());
}
$validator =Validator::make($request->all(), [
'phoneNumber' => [
'max:10',
Rule::unique('users')->ignore($userId,'userId'),
],
]);
if ($validator->fails()) {
//$response['meta'] = array('code' => "422", 'message' => "Error, please try again");
$errors = $validator->errors();
if ($errors->first('phoneNumber')) {
$message = $errors->first('phoneNumber');
}
$this->setMeta("403", $message);
return response()->json($this->setResponse());
}
$homeTown = $request->homeTown;
$heightInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userHeight) {
$userHeight=$request->userHeight;
$heightSplit = explode("'", $userHeight, 2);
$feet = $heightSplit[0];
$inches = $heightSplit[1];
$inch=($feet *12)+$inches;
$heightInCm=$inch*2.54;
}
$verticalInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userVertical) {
$userVertical=$request->userVertical;
$verticalSplit = explode("'", $userVertical, 2);
$feet = $verticalSplit[0];
$inches = $verticalSplit[1];
$inch = ($feet *12)+$inches;
$verticalInCm = $inch*2.54;
}
$data= array(
'profilePic' => $request->profilePic,
'nickName' => $request->nickName,
'phoneNumber' => $request->phoneNumber,
'userHeight' => $heightInCm,
'userWeight' => $request->userWeight,
'userVertical' => $verticalInCm,
'userSchool' => $request->userSchool,
'homeTown' => $homeTown,
'cityId' => $request->cityId,
);
User::where('userId',$request->userId)->update($data);
}
Check if you specifying the correct key for the unique check. Your code says userId is the primary key to compare the given id with, is this correct? If the key is 'id' by default then you can ignore the parameter.
Rule::unique('users')->ignore($$request->userId),
'phoneNumber' => 'max:10|unique:users,id,'.$request->userId,
well after the hell of time spent I finally got the answer.
public function editProfile(Request $request) {
$userId=$request->userid;
$phoneNumber=$request->phoneNumber;
if(!$request){
$this->setMeta("422", "Nothing is there for update");
return response()->json($this->setResponse());
}
$validator = Validator::make(
array(
'phoneNumber' => $phoneNumber,
),
array(
'phoneNumber' =>'size:10', Rule::unique('users')->ignore($request->userId, 'userId'),
)
);
if ($validator->fails()) {
//$response['meta'] = array('code' => "422", 'message' => "Error, please try again");
$errors = $validator->errors();
if ($errors->first('phoneNumber')) {
$message = $errors->first('phoneNumber');
}
$this->setMeta("403", $message);
return response()->json($this->setResponse());
}
$homeTown = $request->homeTown;
$heightInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userHeight) {
$userHeight=$request->userHeight;
$heightSplit = explode("'", $userHeight, 2);
$feet = $heightSplit[0];
$inches = $heightSplit[1];
$inch=($feet *12)+$inches;
$heightInCm=$inch*2.54;
}
$verticalInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userVertical) {
$userVertical=$request->userVertical;
$verticalSplit = explode("'", $userVertical, 2);
$feet = $verticalSplit[0];
$inches = $verticalSplit[1];
$inch = ($feet *12)+$inches;
$verticalInCm = $inch*2.54;
}
$data= array(
'profilePic' => $request->profilePic,
'nickName' => $request->nickName,
'phoneNumber' => $request->phoneNumber,
'userHeight' => $heightInCm,
'userWeight' => $request->userWeight,
'userVertical' => $verticalInCm,
'userSchool' => $request->userSchool,
'homeTown' => $homeTown,
'cityId' => $request->cityId,
);
User::where('userId',$request->userId)->update($data);
$this->setMeta("200", "Profile Changes have been successfully saved");
$this->setData("userDetails", $data);
return response()->json($this->setResponse());
}

Categories