Hateoas Post,Put,Delete PHP, Codeigniter - php

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

Related

Laravel resource collection - paginate - JSON response error

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.

How to write content as JSON format

I have a trouble with JSON in PHP.
I have a JSON structure like this (with some line is const and some line is variable)
{
"user": {
"lam": {---->variable
"\/lam\/files\/a": { ---->variable
"id": 9, ---->variable
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498", ---->variable
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU=" ---->variable
}
}
}
}
}
I don't know how to write this content to file as JSON format like this.
And in a number of case, I must write append to this file and result must like this:
{
"user": {
"lam": {
"\/lam\/files\/a": {
"id": 9,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU="
}
},
"\/lam\/files\/test": {
"id": 12,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-152153961597103330",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "MjdzcDlrenptcG5udzI2MLSQvuGIczY\/SyHZVf9o7e8="
}
}
}
}
}
You could create an array, before to use json_encode():
Here is an example.
// prepare an array with variable (should come from database, or whatever)
$vars = [
[
'user' => 'lam',
'path' => '/lam/files/a',
'id' => 9,
'bucket' => 'lam-15215156681752265498',
'pass' => 'NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU=',
],
[
'user' => 'lam',
'path' => '/lam/files/test',
'id' => 12,
'bucket' => 'lam-152153961597103330',
'pass' => 'MjdzcDlrenptcG5udzI2MLSQvuGIczY/SyHZVf9o7e8=',
]
];
// prepare data to be encoded.
$data = [];
// iterate over the variables,
foreach ($vars as $var) {
// prepare an array for the options
$options = [
"user" => "owncloud",
"bucket" => $var['bucket'], // fill with current variable
"password" => "",
"region" => "regionOne",
"service_name" => "swift",
"tenant" => "owncloud",
"timeout" => "30",
"url" => "http:\/\/controller:5000\/v2.0",
"password_encrypted" =>$var['pass'], // fill with current variable
];
$userdata = [
'id' => $var['id'], // fill with current variable
'class' => '\\OC\\Files\\Storage\\Swift',
'options' => $options, // append options
];
$name = $var['user'];
$path = $var['path'];
$data['user'][$name][$path] = $userdata ; // append to $data array
}
echo json_encode($data, JSON_PRETTY_PRINT);
Outputs:
{
"user": {
"lam": {
"\/lam\/files\/a": {
"id": 9,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\\\/\\\/controller:5000\\\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU="
}
},
"\/lam\/files\/test": {
"id": 12,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-152153961597103330",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\\\/\\\/controller:5000\\\/v2.0",
"password_encrypted": "MjdzcDlrenptcG5udzI2MLSQvuGIczY\/SyHZVf9o7e8="
}
}
}
}
}
You'll need to work with the data as an array (or object) as PHP won't work directly in JSON;
Get your current data from the file into an array:
$data = json_decode(file_get_contents($pathtojsonfile, true));
Append the new data to the array:
$data[] = $newdata;
Then save the newly appended data back to file.
file_put_contents($pathtojsonfile, json_encode($data));

Laravel get the sent data to the request

I am implementing an API using Laravel 5.4 . I want to send the title, description, time and user_id as a JSON and after that to get the JSON response with the input data.
Here is my code:
$title = $request->input('title');
$description = $request->input('description');
$time = $request->input('time');
$user_id = $request->input('user_id');
$meeting = [
'title' => $title,
'description' => $description,
'time' => $time,
'user_id' => $user_id,
'view_meeting' => [
'href' => 'api/v1/meeting/1',
'method' => 'GET1'
]
];
$response = [
'msg' => 'Meeting created',
'meeting' => $meeting
];
return response()->json($response, 201);
After running the server, I make a post request using POSTMAN (body->raw:)
{
"time": "201601301330CET",
"title": "Test meeting 2",
"description": "Test",
"user_id": 2
}
But it return this:
{
"msg": "Meeting created",
"meeting": {
"title": null,
"description": null,
"time": null,
"user_id": null,
"view_meeting": {
"href": "api/v1/meeting/1",
"method": "GET1"
}
}
}
Why the title, description, time and user_id fields are null?
You need to set Postman's content-type dropdown to JSON (application/json). Changing that setting changed the null values in the response to:
{
"msg": "Meeting created",
"meeting": {
"title": "Test meeting 2",
"description": "Test",
"time": "201601301330CET",
"user_id": 2,
"view_meeting": {
"href": "api/v1/meeting/1",
"method": "GET1"
}
}
}

How do you access json nested elements with php

For 24hrs I have been really struggling to find how to access the email and address fields. I think I've tried every combination there is
my last attempt
$obj = json_decode($json);
$emails = $obj->emails->address;
JSON OUTPUT
{
"#http_status_code": 200,
"#visible_sources": 1,
"#available_sources": 1,
"#search_id": "1507310336407868146373527620323253083",
"query": {
"emails": [
{
"address": "paulsparktest#googlemail.com",
"address_md5": "d92590f691eab834586686c563567382"
}
]
},
"possible_persons": [
{
"#search_pointer": "3984f5b332b6efb3331bb137e1e97829ddff0971d9de9347cbd7fb8f82dc68de093a525a66584694339bfe580baff2aacb77954e0f154a1d0bd0a36588094972a72c1c4a63197a9736f6c425afdf66e5d8e52d35073d6499036efe9a234dd1d886f71bf54b9911a19725f118b6cd7bca521c246fe3b890a957596f8236c3c4ac5ba241198c3bdfa2f44a4e361393f1bf407130ffb5b9e2f6b1ccffca87befd0b147e51a12a54773ca31fc1a364b8cde876ca5f42b5d6f0c319f18300cab29fc1",
"names": [
{
"first": "Paul",
"last": "Johnson",
"display": "Paul Johnson"
}
],
"usernames": [
{
"content": "pauljohnson111"
}
],
"gender": {
"#inferred": true,
"content": "male"
},
"addresses": [
{
"country": "GB",
"state": "ENG",
"city": "London",
"display": "London, England"
}
],
"user_ids": [
{
"content": "374967130#twitter"
}
],
"images": [
{
"url": "http://pbs.twimg.com/profile_images/1546592694/Roccc.jpg",
"thumbnail_token": "AE2861B242686E7DDBDF0D814A3486E1D19BE9609F41B4AA71B6D0FEB03454A84C36C69AC788EF676B93C5274D29CD76361050E1F057871D&dsid=39844"
}
]
}
]
}
This will get the address for you
$obj->query->emails[0]->address;
if you want to iterate and get other addresses
foreach ( $obj->query->emails as $email ) {
echo $email->address;
}
You can get address & name via follow code.
// Getting email
echo $data->query->emails[0]->address;
// Getting name
echo $data->possible_persons[0]->names[0]->display;
Full code
$data = '{
"#http_status_code": 200,
"#visible_sources": 1,
"#available_sources": 1,
"#search_id": "1507310336407868146373527620323253083",
"query": {
"emails": [
{
"address": "paulsparktest#googlemail.com",
"address_md5": "d92590f691eab834586686c563567382"
}
]
},
"possible_persons": [
{
"#search_pointer": "3984f5b332b6efb3331bb137e1e97829ddff0971d9de9347cbd7fb8f82dc68de093a525a66584694339bfe580baff2aacb77954e0f154a1d0bd0a36588094972a72c1c4a63197a9736f6c425afdf66e5d8e52d35073d6499036efe9a234dd1d886f71bf54b9911a19725f118b6cd7bca521c246fe3b890a957596f8236c3c4ac5ba241198c3bdfa2f44a4e361393f1bf407130ffb5b9e2f6b1ccffca87befd0b147e51a12a54773ca31fc1a364b8cde876ca5f42b5d6f0c319f18300cab29fc1",
"names": [
{
"first": "Paul",
"last": "Johnson",
"display": "Paul Johnson"
}
],
"usernames": [
{
"content": "pauljohnson111"
}
],
"gender": {
"#inferred": true,
"content": "male"
},
"addresses": [
{
"country": "GB",
"state": "ENG",
"city": "London",
"display": "London, England"
}
],
"user_ids": [
{
"content": "374967130#twitter"
}
],
"images": [
{
"url": "http://pbs.twimg.com/profile_images/1546592694/Roccc.jpg",
"thumbnail_token": "AE2861B242686E7DDBDF0D814A3486E1D19BE9609F41B4AA71B6D0FEB03454A84C36C69AC788EF676B93C5274D29CD76361050E1F057871D&dsid=39844"
}
]
}
]
}';
$data = json_decode($data);
// Getting email
echo $data->query->emails[0]->address;
// Getting name
echo $data->possible_persons[0]->names[0]->display;

format php mysql data injson

My code:
foreach(array_filter($row) as $key => $value) {
$output[$value['phone']]['cards'][] = array(
'email' => $value['email'],
'mobile' => $value['mobile'],
'name' => $value['name']
);}
echo json_encode($output);
Current output:
{
"919898989898": {
"cards": [
{
"email": "vwxy#test.com",
"mobile": "919898989898",
"name": "abcd"
},
{
"email": "pnqr#gmail.com",
"mobile": "8686868686",
"name": "abcd"
}
]
},
"919923717198": {
"cards": [
{
"email": "abcd#gmail.com",
"mobile": "8686868686",
"name": "defg"
},
{
"email": "rstp#test.com",
"mobile": "919898989898",
"name": "defg"
}
]
}
}
Expected output:
{
"phone": [
{
"919923717198": {
"cards": [
{
"email": "abcd#gmail.com",
"mobile": "8686868686",
"name": "defg"
},
{
"email": "rstp#test.com",
"mobile": "919898989898",
"name": "defg"
}
]
}
}
]
}
Use this:
foreach(array_filter($row) as $key => $value) {
$data = [$value['phone']]['cards'][] = array(
'email' => $value['email'],
'mobile' => $value['mobile'],
'name' => $value['name']
);
$output['phone'][] = $data;
}
echo json_encode($output);

Categories