CakePHP API PUT with JSON input - php

I am building an API using CakePHP.
I want to use PUT from my mobile application to update data. The format is JSON as input but $this->data seems to be null.
I call this url (as specified in the docs) from my application:
/recipes/123.json
And in my "recipes" (or whatever) I have the following controller:
function edit($id = null) {
$this->User->id = $id;
if (empty($this->data)) {
$this->data = $this->User->read();
$message = array('StatusCode' => 999, 'ERROR' => "");
} else {
if ($this->User->save($this->data)) {
$message = array('StatusCode' => 200, 'ErrorCode' => "");
} else {
$message = array('StatusCode' => 400, 'ErrorCode' => "UnknownError");
}
}
$this->set(compact("message"));
$this->set('albums', $this->User->Album->find('list'));
}
I correctly receive the JSON response in my application however I get the 999 error - meaning that $this->data is empty.
In my add function in my controller where it receives JSON using POST - the $this->data gets assigned correctly. And oh ye, if I use POST instead of PUT in my edit - the $this->data gets set, but I cannot save the data..
So.. how do I do this ? :S

Insert from luchomolina's link
http://book.cakephp.org/2.0/en/controllers/request-response.html#accessing-xml-or-json-data
//Get JSON encoded data submitted to a PUT/POST action
$data = $this->request->input('json_decode');
and you get your object.
$data->Model->field ...

I haven't tested it, but I think your data is in $this->request->input() or $this->request->data()
More info:
http://book.cakephp.org/2.0/en/controllers/request-response.html#accessing-xml-or-json-data
http://book.cakephp.org/2.0/en/controllers/request-response.html#CakeRequest::data

Related

How to check duplicate title and not save to database in laravel

i have a problem that when i get data from other api and want if same title wont save to api. Each time getting data from the api is 20 and want to save it to the database without duplicate. Please help me. Thank you very much!!!
public function getTitle($title){
$title = $this->posts->where('title', $title)->get();
return $title;
}
public function getApi(Request $request){
$url = "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=87384f1c2fe94e11a76b2f6ff11b337f";
$data = Http::get($url);
$item = json_decode($data->body());
$i = collect($item->articles);
$limit = $i->take(20); // take limited 5 items
$decode = json_decode($limit);
foreach($decode as $post){
$ite = (array)$post;
$hi = $this->getTitle($ite['title']);
dd($ite['title'], $hi);
if($ite['title']==$hi){
dd('not save');
}
else{
dd('save');
}
//dd($hi, $ite['title']);
// create post
$dataPost = [
'title'=>$ite['title'],
'description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']
];
//dd($dataPost);
//$this->posts->create($dataPost);
}
return redirect()->route('posts.index');
}
You can use first or create for saving data in database if title name is new. using firstOrNew you dont have to use any other conditions
for example:-
$this->posts->firstOrCreate(
['title' => $ite['title']],
['description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']]);
firstOrNew:-
It tries to find a model matching the attributes you pass in the first parameter. If a model is not found, it automatically creates and saves a new Model after applying any attributes passed in the second parameter
From docs
If any records exist that match your query's constraints, you may use
the exists and doesntExist methods
if($this->posts->where('title', $title)->doesntExist())
{
// save
} else {
// not save
}

CodeIgniter - validation not happens

I am doing a validation using Code Igniter. I have a simple form which used to create / update a product record.
public function productSave($params) {
if (!$this->validate($params)) {
return FALSE;
}
$id_col_value = $params['product_id'];
if ($id_col_value) {
// update
$this->db->where("product_id", $id_col_value);
return $result = $this->db->update("product", $params);
} else {
// insert
return $result = $this->db->insert("product", $params);
}
}
My validation function looks like this,
protected function validate($params) {
$this->form_validation->set_rules("name", "", "trim|required");
$this->form_validation->set_data($params);
if ($this->form_validation->run() == FALSE){
$errors = $this->form_validation->error_array();
if ( $errors ){
return FALSE;
}
}
return TRUE;
}
Now the problem
When inserting (when product_id is null) it validates. But when we have a product_id it does not validates.
My payload ($params) looks like this,
Array
(
[product_id] => 1 // this is NULL when we do inserting
[name] => Test Name
)
I can't figure out what I am doing wrong here and why the validation not work for updating. I use the same code for both cases.
Please Help! Thanks in advance!
I figure it out.
"We have to call the set_data() method before defining any validation
rules."
Which is in the Documentation of CI.
So, basically, I call $this->form_validation->set_data($params); first
and then, I call $this->form_validation->set_rules("name", "", "trim|required");.
This will solve the problem.
Hope this helps anyone with the same error!!!
Check your params array. I have checked it using $params = array("product_id" => 34, "name" => "Test Name") & it's working perfectly.
If you have no inserted data with that product_id, it will not work. Suppose you have passed product_id=3 & this id is not available in table. Then how should it work?

Not receiving URL variables in controller with GET, codeigniter

I'm not receiving variables in my controller from a URL from Paypal indicating a successful transaction. They appear in the URL fine but my controller is not receiving them for some odd reason. I think the code is absolutely correct. What could be the reason?
Example:
Received URL: http://example.com/Paypal/success?tx=8FA47070HF454623K&st=Completed&amt=20%2e00&cc=USD&cm=&item_number=
Controller, PHP:
function success(){
//get the transaction data
$paypalInfo = $this->input->get();
$data['item_number'] = $paypalInfo["item_number"];
$data['txn_id'] = $paypalInfo["tx"];
$data['payment_amt'] = $paypalInfo["amt"];
$data['currency_code'] = $paypalInfo["cc"];
$data['status'] = $paypalInfo["st"];
//pass the transaction data to view
$this->load->view('paypal/success', $data);
}
I get this result for all variables:
Looks like item_number is not set. Performing a GET on it can cause an error.
You are using a class function to obtain the $_GET items.
Within the function $this->input->get() you should check if the var is available (if(isset($_GET[..]))) and otherwise return a default, so you don't run into these problems.
On the other hand, it seems that you don't submit a item_number to Pay Pal. May also be a problem for processing your order later on in the script and backtracing it to the original...
---- ALSO SEE ANSWER BELOW ----
Paypal sends POST vars...
Remember Paypal not send data via URL, So you couldn't receive data via GET method. You should try this
$paypalInfo = $this->input->post();
instead what you are using now. If it not works then use following
$paypalInfo = $_POST;
it will must work
Just processing $_POST gives you a huge security risk! Also for $_GET. Change $_POST to $_GET below to use $_GET in stead of $_POST.
I would suggest at least the following;
foreach ($_POST as $key->$value)
{
$cleankey = addslashes($key);
$paypalInfo[$cleankey] = addslashes($value);
}
Then;
$req_keys = array(
'item_number' => 'item_number',
'txn_id' => 'tx',
'payment_amt' => 'amt',
'currency_code' => 'cc',
'status' => 'st',
);
$data = array();
$error = array();
foreach($req_keys as $req_data_key=>$req_paypalinfo_key )
{
if(isset($paypalInfo[$req_paypalinfo_key]))
{
$data[$req_data_key] = $paypalInfo[$req_paypalinfo_key];
}
else
{
$error[] = "missing POST data:".$req_paypalinfo_key;
}
}
if(count($error) > 0)
{
var_dump($error);
}
else
{
$this->load->view('paypal/success', $data);
}
This will give you insight if your required info is there and also gives you some protection against SQL injection.

CakePHP $this->Auth->user("id") always return null?

I have a function that I use to get the user id of Auth component. It works fine without use return json_encode. The problem is that I need this works with json_encode because I get values from ajax request.
Using json_encode it always return null to id and I can't understand why does it occur. The problem is with the function indexAjax() below.
How could I use $this->Auth->user("id") with json_encode and it not return null ?
Trying.
//using $this->set it works fine
public function index() {
$id = $this->Auth->user("id");
$empresas = $this->Empresa->find('all', array(
'fields'=>array("id", "nomeFantasia", "cnpj",
"telefone1", "telefone2", "celular", "aberto"),
'conditions'=>array("users_id = "=> $id)
));
debug($id) or die;
//$this->set(compact('empresas'));
}
//with json_encode always return null
public function indexAjax() {
$this->autoRender = false;
$id = $this->Auth->user("id");
$empresas = $this->Empresa->find('all', array(
'fields'=>array("id", "nomeFantasia", "cnpj",
"telefone1", "telefone2", "celular", "aberto"),
'conditions'=>array("users_id = "=> $id)
));
return json_encode($id);
}
solved the problem. My solution was when user make login I get the user id and write in session so when I need this id I get from session directly and not from AuthComponent.
It works.

How to pass data from one function to another in codeigniter by using session?

Am trying to pass some data from one function to another when i set the data into session and print the session data i get the correct data, but whe trying to use the data in another function i get the word "Assets" i dont know where this word come from. Session library is auto loaded.Any help please.
These are my codes:
First function:
$client_id = $this->uri->segment(3);
$sess_array = array(
'cl_id' => $client_d,
'selected_client'=>TRUE,
);
$this->session->set_userdata('selected_client',$sess_array);
Second function:
$client_sess = $this->session->userdata('selected_client');
$client_id= $client_sess['cl_id'];
Try this i think this will give you some idea.
function one(){
$client_id = $this->uri->segment(3);
$sess_array = array(
'cl_id' => $client_d,
'selected_client'=>TRUE,
);
$this->two($sess_array);
}
function two($id){
$client_id= $id;
}
Here is what the Model looks like:
function getResponse($gettingresponse)
{
$enrollresponse=$gettingresponse['sendresponse'];
return $enrollresponse;
}
The Controller is as follows:
public function Register()
{
   $this->load->view('firstview');
   $this->load->view('secondview');
   if($_POST) {
       $gettingresponse=array(
           'sendresponse'=>$_POST['source'],
           'receiverresponse'=>$_POST['destination']
       );
       $registration_confirm=$this->systemModel->responselogin($gettingresponse);
       $resposeflag=$this->systemModel->getEmail($gettingresponse);
       $data['resposeflag']=$gettingresponsevalue;
       if($registration_confirm){
           $this->token($data);
       }
   }
   $this->load->view('thirdview');
}
public function token($data=array())
{
   $this->load->view('firstview');
   $data['resposeflag'];
   $this->load->view('token',$data);
   $this->load->view('thirdview');
}
The following View shows the data that has been passed between the functions of the Controller.
<?php
echo form_input(array('name'=>'source','readonly'=>'true','value'=>$resposeflag));
?>

Categories