Related
can anybody give example of how to code POST, PUT, Delete Hateoas PHP in Codeigniter, I have 2 tables, author(AuthorID is primary key, BookID I foreign key), book(BookID is primary key)
I have Index_get
public function index_get(){
$id = $this->get('AuthorID');
$author =[];
if ($id ==""){
$data = $this->db->get("author")->result();
foreach($data as $row=>$key):
$author[]=["AuthorID"=>$key->AuthorID,
"AuthorName"=>$key->AuthorName,
"_link"=>[(object)["href"=>"book/{$key->BookID}",
"rel"=>"book",
"type"=>"GET"]],
"BirthPlace"=>$key->BirthPlace,
"Email"=>$key->Email,
"Education"=>$key->Education,
"Phone"=>$key->Phone,
"Address"=>$key->Address,
"Nationality"=>$key->Nationality
];
endforeach;
}
else {
$this->db->where("AuthorID","$id");
$data = $this->db->get("author")->result();
}
$result = ["took"=>$_SERVER["REQUEST_TIME_FLOAT"],
"code"=>200,
"message"=>"Show Data Success",
"author"=>$author];
$this->response($result, 200);
}
and it success
"took": 1637045427.669679,
"code": 200,
"message": "Show Data Success",
"author": [
{
"AuthorID": "A1",
"AuthorName": "Jack Dane",
"_link": [
{
"href": "book/1",
"rel": "book",
"type": "GET"
}
],
"BirthPlace": "London",
"Email": "Jackdane#gmail.com",
"Education": "Bachelor At Univercity Of Canada",
"Phone": "09199191",
"Address": "4457 Grey Fox Farm Road, Houston, Texas",
"Nationality": "America"
},
{
"AuthorID": "A2",
"AuthorName": "Michael Dendy",
"_link": [
{
"href": "book/2",
"rel": "book",
"type": "GET"
}
],
"BirthPlace": "New York",
"Email": "Michaeldendy#gmail.com",
"Education": "Bachelor At Univercity Of California",
"Phone": "09188181",
"Address": "2602 Farnum Road, New York, New York",
"Nationality": "America"
},
{
"AuthorID": "A3",
"AuthorName": "Dumando",
"_link": [
{
"href": "book/3",
"rel": "book",
"type": "GET"
}
],
"BirthPlace": "Jakarta",
"Email": "Dumando#gmail.com",
"Education": "Bachelor At Indonesia Univercity",
"Phone": "012929919",
"Address": "Jl Cendrawaih 919 Jakarta",
"Nationality": "Indonesia"
},
{
"AuthorID": "A4",
"AuthorName": "dono",
"_link": [
{
"href": "book/4",
"rel": "book",
"type": "GET"
}
],
"BirthPlace": "Beijing",
"Email": "dono#gmail.com",
"Education": "Bachelor at ITS",
"Phone": "0919191",
"Address": "Jl. MTHaryono",
"Nationality": "china"
}
]
}
But when I try to POST in postman it gives me the error "Column 'AuthorID' cannot be null". AuthorID is the primary key.it give me the error "Column 'AuthorID' cannot be null" but AuthorID already has input, I just wanna change BirthPlace.
function index_post() {
$author = array(
'AuthorID' => $this->post('AuthorID'),
'AuthorName' => $this->post('AuthorName'),
'BookID' => $this->post('BookID'),
'BirthPlace' => $this->post('BirthPlace'),
'Email' => $this->post('Email'),
'Education' => $this->post('Education'),
'Phone' => $this->post('Phone'),
'Address' => $this->post('Address'),
'Nationality' => $this->post('Nationality'));
$insert = $this->db->insert('author', $author);
if ($insert) {
$result = ["took"=>$_SERVER["REQUEST_TIME_FLOAT"],
"code"=>200,
"message"=>"Add Data Success",
"author"=>$author];
$this->response($result, 200);
} else {
$result = ["took"=>$_SERVER["REQUEST_TIME_FLOAT"],
"code"=>200,
"message"=>"Failed Add Data",
"author"=>$author];
$this->response($result, 502);
}
}
when I try PUT in postman it give me success message but the data is not update. AuthorID is null, BoodID is null, i already input AuthorID, BookID in postman and still data cannot update,
function index_put() {
$id = $this->put('AuthorID');
$author = array(
'AuthorID' => $this->put('AuthorID'),
'AuthorName' => $this->put('AuthorName'),
'BookID' => $this->put('BookID'),
'BirthPlace' => $this->put('BirthPlace'),
'Email' => $this->put('Email'),
'Education' => $this->put('Education'),
'Phone' => $this->put('Phone'),
'Address' => $this->put('Address'),
'Nationality' => $this->put('Nationality'));
$this->db->where('AuthorID', $id);
$update = $this->db->update('author', $author);
if ($update) {
$result = ["took"=>$_SERVER["REQUEST_TIME_FLOAT"],
"code"=>200,
"message"=>"Data Update Success",
"author"=>$author];
$this->response($result, 200);
} else {
$result = ["took"=>$_SERVER["REQUEST_TIME_FLOAT"],
"code"=>200,
"message"=>"Failed Update Data",
"author"=>$author];
$this->response($result, 502);
}
}
result index_put
{
"took": 1637045848.425828,
"code": 200,
"message": "Data Update Success",
"author": {
"AuthorID": null,
"AuthorName": "Jack Dane",
"BookID": null,
"BirthPlace": "Jakarta",
"Email": "Jackdane#gmail.com",
"Education": "Bachelor At Univercity Of Canada",
"Phone": "09199191",
"Address": "4457 Grey Fox Farm Road, Houston, Texas",
"Nationality": "America"
}
}
and when I try DELETE it gives me "status": "Success Delete Data" but the data is not removed when I check in PHPMyAdmin.
function index_delete() {
$id = $this->delete('AuthorID');
$this->db->where('AuthorID', $id);
$delete = $this->db->delete('author');
if ($delete) {
$this->response(array('status' => 'Success Delete Data'), 200);
}
else{
$this->response(array('status' => 'fail Delete Data', 502));
}
}
Here I am sharing response of API where i want to show to show specialization name in 'doctor_detail_data' array instead of "doctor_requests" array. In laravel using foreach loop . Below is my code:
$data['doctor_requests'] = DoctorRequests::where('caretaker_id', $caretaker_id)
->whereIn('status', $whereInArray)
->with('doctorUserData')->with('doctorDetailData')->get();
foreach ($data['doctor_requests'] as $key => $value) {
$data['doctor_requests'][$key]['specialization'] = Helpers::getSpecialisationName($value['doctorDetailData']['specialization']);
}
return ['code' => 200, 'status' => 'success', 'data' => $data, 'message' => 'Record fetched successfully.'];
Response :
{
"code": 200,
"status": "success",
"data": {
"doctor_requests": [
{
"id": 142,
"doctor_id": 432,
"caretaker_id": 429,
"patient_id": 433,
"specialization": "Oncology (Cancer Care)",
"doctor_user_data": {
"id": 432,
"name": "Sandeep Singh",
},
"doctor_detail_data": {
"id": 50,
"user_id": 432,,
"specialization": "3",
}
]
},
"message": "Record fetched successfully."
}
I am trying to add a customer(Podio item) to my Podio app. This customer is being added programmatically from within a php application. There are several fields present on the customer: Name, Address, Email, Title, Phone Number, and an array of Tags. When a tag is added the color changes to highlight it.
In previous iterations I have been successful adding a different tag(newsletter_subscribed) using the ID of the tag value that I want highlighted. Now when I try to add another tag(hospital, clinic, or urgent_care) it is throwing a PodioBadRequestError. The error cited is that the ID being used is and invalid type(integer).
I got the values of the tag ID's by looking at the JSON returned when an existing customer created manually within my Podio customer application. When I look at the ID fields in the JSON they are most definitely integers, I have tried strings as well. Everything I try throws the 400 Bad Request on the ID that I am trying to add.
I cannot for the life of me figure out why it is throwing the error when I add the tag ID's.
Below is the way that the application is put together:
This is the code that builds and sends the request:
public function addToPodio()
{
$address = $this->Address . ", " .
$this->Address2 . ", " .
$this->City . ", " .
$this->State . " " .
$this->Zip;
$item = [
'fields' => [
'name' => $this->PrimaryContactFirstName,
'last-name' => $this->PrimaryContactLastName,
'email-address' => ['type' => 'work', 'value' => $this->PrimaryContactEmail],
'phone-number' => ['type' => 'work', 'value' => $this->PrimaryContactPhone],
'address' => $address,
'organization' => [$this->CompanyName],
'tags-2' => []
],
];
if ($this->Newsletter && defined('PODIO_NEWSLETTER_TAG_ID')){
$item['fields']['tags-2'][] = PODIO_NEWSLETTER_TAG_ID;
}
if($this->OrganizationType && defined('PODIO_ORGANIZATION_TYPE_ID')){
if($this->OrganizationType == "Clinic"){
$item['fields']['tags-2'][] = PODIO_ORGANIZATION_TYPE_CLINIC_TAG_ID;
}
else if($this->OrganizationType == "Hospital"){
$item['fields']['tags-2'][] = PODIO_ORGANIZATION_TYPE_HOSPITAL_TAG_ID;
}
try {
//This is where the request is being made
$customer = PodioItem::create(PODIO_CUSTOMER_APP_ID, $item);
$this->PodioId = $customer->item_id;
$this->write();
} catch (Exception $e) {
error_log('We encountered an error adding your item to Podio' . $e);
return 'An error occurred while updating Podio. Please try again. If the error...';
}
This is the PHP $item that is being passed to the request that gets sent to the Podio API:
Array
(
[fields] => Array
(
[name] => Joe
[last-name] => Test
[phone-number] => Array
(
[type] => work
[value] => 8675309
)
[address] => 123 Main Road, , East Test, NY 12345
[organization] => Array
(
[0] => Another Test
)
[tags-2] => Array
(
[0] => 16
[1] => 96
)
)
)
This is the config file with the all of the constants, secrets tokens and ID's needed to connect to the Podio API, authenticate and all of that stuff. Obfuscated Example below:
define('PODIO_CUSTOMER_APP_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CUSTOMER_APP_TOKEN', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CLIENT_SECRET', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CLIENT_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_ORGANIZATION_TYPE_ID', 'xxxxx-obfuscated-xxxx');
define('PODIO_NEWSLETTER_TAG_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_ORGANIZATION_TYPE_CLINIC_TAG_ID', 'xxxxx-obfuscated-xxxxx');
Podio::setup(PODIO_CLIENT_ID, PODIO_CLIENT_SECRET, [
'session_manager' => Injector::inst()->get(PodioSession::class),
'curl_options' => array(),
]);
Below is the JSON that I used to get the values of the ID's. I got this from a postman request to the API. The basic form of the request without all of the authentication present looked like:
podio.com/MY_PODIO_ACCOUNT_NAME/app/APPLICATION_ID/item/ITEM_ID
Please note: I removed many of the main fields like Address and Organization for brevity's sake, so it won't match completely the PHP request object above.
{
"id": 0000,
"item_id": 00000,
"revision": 0,
"app": null,
"app_item_id": 00000,
"app_item_id_formatted": "PODIO_Field_ID:00000",
"external_id": null,
"title": "TEST ITEM",
"fields": [
{
"id": 0000,
"field_id": 0000,
"type": "text",
"external_id": "name",
"label": "First Name",
"values": [
{
"value": "Joe"
}
],
"config": {
"settings": {
"format": "plain",
"size": "small"
},
"mapping": "contact_name",
"label": "First Name"
},
"humanized_value": "Joe"
},
{
"id": 0000,
"field_id": 0000,
"type": "text",
"external_id": "last-name",
"label": "Last Name",
"values": [
{
"value": "<p>Test<br /></p>"
}
],
"config": {
"settings": {
"format": "html",
"size": "large"
},
"mapping": null,
"label": "Last Name"
},
"humanized_value": "Test"
},
{
"id": 0000,
"field_id": 0000,
"type": "phone",
"external_id": "phone-number",
"label": "Phone Number",
"values": [
{
"type": "work",
"value": "867-5309"
}
],
"config": {
"settings": {
"call_link_scheme": "callto",
"possible_types": [
"mobile",
"work",
"home",
"main",
"work_fax",
"private_fax",
"other"
]
},
"mapping": "contact_phone",
"label": "Phone Number"
},
"humanized_value": "8675309"
},
{
"id": 11111,
"field_id": 11111,
"type": "category",
"external_id": "tags-2",
"label": "Tags",
"values": [
{
"value": {
"status": "active",
"text": "Clinic",
"id": 16,
"color": "DCEBD8"
}
},
{
"value": {
"status": "active",
"text": "Newlsetter_subscribed",
"id": 96,
"color": "DCEBD8"
}
}
],
"config": {
"settings": {
"multiple": true,
"options": [
{
"status": "active",
"text": "Mktng:test1/2020",
"id": 150,
"color": "DCEBD8"
},
{
"status": "active",
"text": "Mktng:Test2/2020",
"id": 3,
"color": "DCEBD8"
},
{
"status": "active",
"text": "SampleTest",
"id": 48,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Test Center",
"id": 139,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Sample Center",
"id": 99,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Testing Center",
"id": 140,
"color": "DCEBD8"
}
],
"display": "inline"
},
"mapping": null,
"label": "Tags"
},
"humanized_value": "Clinic; Newsletter;"
}
this JSON continues for pages and pages, I only included the relevant fields for my question.
It looks like the error is being thrown because of the organization value, not the tags value.
For a category field, an array of integer indices is correct.
[tags-2] => [ 16, 96 ]
For an app field, you need to provide an array of integer item ID's.
[organization] => [ 12345 ]
But your code above is sending an array of strings:
[organization] => [ "Another Test" ]
That won't work.
This is the array:
$response = array( 'message-count' => '1', 'messages' => array ( 0 => array ( 'to' => '12345667888', 'message-id' => 'XXXXXXXXXXX', 'status' => '0', 'remaining-balance' => '9.26820000', 'message-price' => '0.03330000', 'network' => '11111', ), ), );
What code do I use to get like, for example, the 'message-id' 's data?
I've tried $response->messages["message-id"];
but what I get is Trying to get property 'messages' of non-object
Tried a lot of others as well they are all returning the same error
I am quite new to this so I hope I could get some help here
Sorry:
Vardump gives me this, made a mistake with the code above
'{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}'
response is an array, you can't get messages like -> , You should get message-id by this way:
$jsonStr = '{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}';
$data = json_decode($jsonStr);
$messageId = $data->messages[0]->{'message-id'};
echo $messageId; //or var_dump($messageId)
Your array contains non-object values so you can retrieve the values as below.
<?php
$response = array('message-count' => '1', 'messages' => array(0 => array('to' => '12345667888', 'message-id' => 'XXXXXXXXXXX', 'status' => '0', 'remaining-balance' => '9.26820000', 'message-price' => '0.03330000', 'network' => '11111',),),);
echo $response['messages'][0]['message-id'];
// Output
// XXXXXXXXXXX
I would use array_column function like this
array_column($response['messages'], 'message-id');
$msg = '{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}';
$data = json_decode($msg);
$messageId = $data->messages[0]->{'message-id'};
var_dump($messageId);
If you have more than one message in the list then,
$messages = $data->messages;
foreach ($messages as $index => $message) {
var_dump($message); // whole message detail
var_dump($message->{'message-id'});// message-id
}
I want to do paging at the Laravel API. As a result, I want to get data and status code type.
Controller :
public function index()
{
$data = PersonCollection::collection(Person::paginate(2));
return response()->json($data, 200);
}
PersonCollection Resource :
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'phone' => $this->phone,
'city' => $this->city,
'href' => [
'link' => route('person.show', $this->id),
],
];
}
Output :
https://i.hizliresim.com/LvlBzj.png
[
{
"id": 1,
"first_name": "Burak Ali",
"last_name": "Ildır",
"email": "burak#gmail.com",
"phone": "376.395.7233",
"city": "Koelpinstad",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/1"
}
},
{
"id": 2,
"first_name": "Vena",
"last_name": "Spinka",
"email": "shields.carolyn#example.org",
"phone": "716-268-7788 x092",
"city": "South Gudrunbury",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/2"
}
}
]
But I want.
https://i.hizliresim.com/LvlBWo.png
{
"data": [
{
"id": 1,
"first_name": "Burak Ali",
"last_name": "Ildır",
"email": "burak#gmail.com",
"phone": "376.395.7233",
"city": "Koelpinstad",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/1"
}
},
{
"id": 2,
"first_name": "Vena",
"last_name": "Spinka",
"email": "shields.carolyn#example.org",
"phone": "716-268-7788 x092",
"city": "South Gudrunbury",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/2"
}
}
],
"links": {
"first": "http://127.0.0.1:8000/api/v1/person?page=1",
"last": "http://127.0.0.1:8000/api/v1/person?page=26",
"prev": null,
"next": "http://127.0.0.1:8000/api/v1/person?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 26,
"path": "http://127.0.0.1:8000/api/v1/person",
"per_page": 2,
"to": 2,
"total": 52
}
}
I want other page links. But when I convert it to JSON data, links and metadata do not come.
A resource collection describes how a collection of models will be transmitted as JSON.
You seem to be using it for an individual model. What you need is:
public function toArray($request)
{
return $this->collection->map(function ($person) {
return [
'id' => $person->id,
'first_name' => $person->first_name,
'last_name' => $person->last_name,
'email' => $person->email,
'phone' => $person->phone,
'city' => $person->city,
'href' => [
'link' => route('person.show', $person->id),
],
];
});
}
However the recommended way is to make a PersonResource instead in the same namespace and implement the toArray($request) in that class:
Person
class Person extends Resource //The name is important
{
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'phone' => $this->phone,
'city' => $this->city,
'href' => [
'link' => route('person.show', $this->id),
],
];
}
}
PersonCollection
class PersonCollection extends ResourceCollection
{
// This class is intentionally empty
}
Finally you should let Laravel handle how to make the response:
public function index()
{
$data = PersonCollection::collection(Person::paginate(2));
return $data->toResponse();
}
The default behaviour of the resource collection is to look for a resource which is named like the collection but with the Collection part removed (in this case PersonCollection will look for a Person resource).
This should ensure each model is converted according to the resource and the pagination behaviour is maintained.