how to send api response array in code codeigniter? - codeigniter

I am creating api in codeigniter in which i am checking both email and mobilenumber field for updating & in that check it for both field. my single message is go to response but in both casess how can i send both email and mobile number is exists
if((isset($postData['email'])) && $postData['email']!="")
{
$message["email_unique"]='Email already exists';
return $this->response(array("status" => "400", "message" =>$message), 400);
}
if((isset($postData['mobileNumber'])) && $postData['mobileNumber']!="")
{
$mobilenumber=$postData['mobileNumber'];
$message["mobilenumber_unique"]='Mobile Number already exists';
return $this->response(array("status" => "400", "message" =>$message), 400);
}

Check this code
"400",
"message" =>$message
]);
exit;
} else {
$message['success'] = "Successful"; // success messsage if needed
$data = null; // whatever data you need to pass in success resposne - either fetch from Database or hardcoded
// validated flow
echo json_encode([
"status" => "200",
"message" =>$message,
"data" => $data
]);
}
?>
==================================
Success resposne:
{"status":"200","message":{"success":"Successful"},"data":null}
Failed response:
{"status":"400","message":{"error_email":"Email address required.","error_mobile":"Mobile number required."}}
If email exists and mobile number empty then
Failed response:
{"status":"400","message":{"error_mobile":"Mobile number required."}}

Related

Laravel API - Display all districts when state field is empty

Below given is my code to display the specific districts of an inputted state. But in this code itself, i want to display all districts in the db if the state field is empty. How to modify my code to get such an output. So, my desired API works such that it returns all the districts when the api is called. And only if the state field is inputted, it shows the particular districts specific to it. Help me with ur suggestions.
public function state_lookup(Request $request)
{
$validator = Validator::make
($request->all(),
[
'state' => 'string',
]
);
if ($validator->fails()) {
return response()->json(
[$validator->errors()],
422
);
}
if(empty($request->state)){
$dist=PersonalDetails::get(['district']);
return response()->json($dist);
}
$data = PersonalDetails::where('state',$request->state)->get(['district']);
// dd($data);
if(count($data)){
return response()->json(['message'=>'success','data'=>$data]);
}
else{
return response()->json(['message'=>'Invalid State']);
}
}
in failure case,I am getting json result as below
{
"message": "success",
"data": []
}
it shows "success" instead of "invalid state"
You can use when
$data = PersonalDetails::when(!empty($request->state),function ($query)use($request){
$query->where('state',$request->state);
})->get(['district']);
or
$data = PersonalDetails::where(function ($query)use($request){
if(isset($request)&&!empty($request)){
$query->where('state',$request->state);
}
})->get(['district']);
To avoid 0 key in response change like below
if(count($data)){
return response()->json(['message'=>'success','data'=>$data]);
}
Try with this,
//In your controller
$request->validate([
'state' => 'string'
]);
// $request->validate it self return error messages you have to display
// for an example (write below code in your blade file)
#error('state')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
// write below code in your controller file
$details = PersonalDetails::select('district');
$details->where(function($query) use($request) {
if (isset($request->state) && $request->state != '') {
$query->where('state', $request->state);
}
// do what you want to filter in your query like above
});
$data = $details->get();

pagination is not working properly for Twilio in Laravel

I am trying to paginate the records for Twilio and after taking the reference from here
I have added the next page and previous page url and its showing successfully but when I am opening the url, its showing the error i.e.
"code": 20003,
"detail": "Your AccountSid or AuthToken was incorrect.",
"message": "Authentication Error - No credentials provided",
"more_info": "https://www.twilio.com/docs/errors/20003",
"status": 401
Here is my code :
public function listcallsapp(Request $request){
$calls = $this->twilio->calls->page([], 50);
$data = [];
$i = 0;
foreach($calls as $call){
$data[$i]['sid'] = $call->sid;
$data[$i]['from'] = $call->from;
$data[$i]['to'] = $call->to;
$data[$i]['direction'] = $call->direction;
$data[$i]['status'] = $call->status;
$data[$i]['duration'] = $call->duration;
$i++;
}
return response()->json([
'message'=>'Call Logs!',
'code'=>200,
'prev' => $calls->getPreviousPageUrl(),
'next' => $calls->getNextPageUrl(),
'data'=>$data,
'status'=>'success'
]);
}
Where I am missing, please help me out. Also, If any other way, please suggest.

Uploading file to onedrive using microsoft graph api

I am trying to uploading a video file to onedrive using the microsoft graph api with the php sdk implementation in laravel.
Code details as below
// Get the access token from the cache
$tokenCache = new TokenCache();
$accessToken = $tokenCache->getAccessToken();
$file_name = 'new_video.mp4';
$media_path = storage_path('video.mp4');
// Create a Graph client
$graph = new Graph();
$graph->setAccessToken($accessToken);
//create post request
$postData = json_encode([ 'items' =>
[
"#odata.type" => "microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior" => "rename",
"name" => $file_name
]
]);
//dd(json_encode($postData));
try {
$post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);
} catch (\Illuminate\Http\Client\RequestException $e) {
dd($e);
}
Not sure what should go into the item path too, i tried using the folder name but got error and i also tried excluding the item path but still got an error.
This is the error I am getting
Client error: `POST https://graph.microsoft.com/v1.0/drive/root/createUploadSession` resulted in a `400 Bad Request` response: {
"error": {
"code": "BadRequest",
"message": "Unable to read JSON request payload. Please ensure Content-T (truncated...)
Json Encode of the request data is also as below and I cant figure out the problem...
{"items":
{
"#odata.type":"microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior":"rename",
"name":"new_video.mp4"
}
}
According to this example given on msgraph-sdk-php repository you don't need to json_econde your body data. The sdk will do it for you.
So your code should looks like this:
// Get the access token from the cache
$tokenCache = new TokenCache();
$accessToken = $tokenCache->getAccessToken();
$file_name = 'new_video.mp4';
$media_path = storage_path('video.mp4');
// Create a Graph client
$graph = new Graph();
$graph->setAccessToken($accessToken);
//create post request
$postData = [ 'items' =>
[
"#odata.type" => "microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior" => "rename",
"name" => $file_name
]
];
try {
$post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);
} catch (\Illuminate\Http\Client\RequestException $e) {
dd($e);
}

Laravel Json Response Not working as expected

Unable to get response while response object is empty. Works perfect when the object has data returned.
public function show($id)
{
$associates = Associate::find_by_id($id);
if(count($associates)<1)
{
$output = array('message' => 'No Records Found');
$status = 204;
}
else{
$output = array('message' => 'success','data'=>$associates);
$status = 200;
}
return response()->json($output,$status);
}
There is no response when the $associate object is empty.
Response when $associate is not empty:
{
"message": "success",
"data": [
{
"first_name": "xxx",
"last_name": "xxx",
"mobile": xxxxxxxxxx,
"email": "xxxxxx#xxxxx",
"city": "xxxxx",
"state": "xxxxxx",
"pincode": "xxxxx"
}
]
}
I had the same issue for status code 204 .
I believe this is caused here. The Illuminate\Foundation\Application class is then catching this and throwing an HttpException.
I believe the simplest fix would be to make the controller return the following instead:
return Response::make("", 204);
Returning a empty message.
check status_code in your code to display message in frontend .
It will be easier if you use route model binding to find the ID of the record. For more information check https://laravel.com/docs/5.7/routing#route-model-binding.
I think the snippet below should work.
if ($associates) {
$output = array('message' => 'success','data'=>$associates);
$status = 200;
} else {
$output = array('message' => 'No Records Found');
$status = 204;
}
I've rewrote the function for your reference.
BTW. If the function return only one record, use singular noun for variable name in general.
public function show($id)
{
// Use find() instead of find_by_id()
$associate = Associate::find($id);
// $associate will be null if not matching any record.
if (is_null($associate)) {
// If $associate is null, return error message right away.
return response()->json([
'message' => 'No Records Found',
], 204);
}
// Or return matches data at the end.
return response()->json([
'message' => 'success',
'data' => $associate,
], 204);
}

Updates records more than one time on laravel

I am trying to update values in laravel. I have a userupdate profile api which I can update the values first time with given parameters and their values but 2nd time when I update same values it gives me user profile does not exist.
My Code is :
public function UpdateUserProfile(Request $request)
{
$id = $request->input('id');
$client_gender = $request->input('client_gender');
$client_age = $request->input('client_age');
$client_weight = $request->input('client_weight');
$client_height = $request->input('client_height');
$client_dob = $request->input('client_dob');
$profile= DB::table('clients')
->where('id',$id)
->update(['client_gender'=>$client_gender,'client_age'=>$client_age,'client_height'=>$client_height,'client_weight'=>$client_weight,'client_dob'=>$client_dob]);
if($profile)
{
$resultArray = ['status' => 'true', 'message' => 'User profile updated Successfully!'];
return Response::json( $resultArray, 200);
}
$resultArray = ['status' => 'false', 'message' => 'User profile does not exist!'];
return Response::json($resultArray, 400);}
first time when I update the value it gives me the response like this:
{
"status": "true",
"message": "User profile updated Successfully!"
}
and when I hit the update request through a postman it gives a 400 Bad request and response is :
{
"status": "false",
"message": "User profile does not exist!"
}
I'd recommend rewriting that function to look like the following; mostly because it reads better and uses the Model methods that are more commonly found in Laravel
public function UpdateUserProfile(Request $request)
{
// this code fails if there is no client with this id
$client = App\Client::findOrFail($request->id);
// attach new values for all of the attributes
$client->client_gender = $request->input('client_gender');
$client->client_age = $request->input('client_age');
$client->client_weight = $request->input('client_weight');
$client->client_height = $request->input('client_height');
$client->client_dob = $request->input('client_dob');
// save
$client->save();
return ['status' => 'true', 'message' => 'User profile updated Successfully!'];
}

Resources