Not getting data from api in cakephp - cakephp

I am trying to make an api. problem is it does not response value. It shows null. I am using postman. Here I'm keeping json in body with json format. My goal is to show the name when I hit api. Here is data which I am passing
{
"username":"xxxx"
}
In my api controller
public function getName()
{
if ($this->request->is('post')) {
$name = $this->request->data('username');
$val = ["username" => $name];
$this->response->type('json');
$this->response->body(json_encode($val));
return $this->response;
}
}

CakePHP is still PHP. At the very top of the function, I would do a pr($_POST); and see what's coming through. If nothing, are you definitely POSTing? If you do see some data, is it prepended with a model name, or something else, which would cause $this->request->data('username') to return null? At the very least you can make sure you're actually posting to the right place, and go from there.

try this (for CakePHP > 3):
if ($this->request->is('post')) {
$this->viewBuilder()->className('Json');
$name = $this->request->data('username');
$val = ["username" => $name];
$this->set(compact('val'));
$this->set('_serialize', ['val']);
}

Did you try
$input = $this->request->input('json_decode');
pr($input);

Related

How to pass array value from view to another view Laravel 5.7

I want to get the value from the array I've passed from the first view to another view.
I found this works by using route (not url), but I don't know how to get it without parameter in the controller.
Please help me within the right syntax.
This is the latest code I've tried
$id = $request->id;
if($request->has('download', 'id')){
$pdf = PDF::loadView('pdfview');
return $pdf->download('pdfview.pdf',['id'=>$id])->with('id',$id);}
This is my code *used to download pdf file from a view
Controller
public function pdfview(Request $request)
{
$items = DB::table("items")->get();
view()->share('items',$items);
$id = $request->only(['id']);
if($request->has('download', 'id')){
$pdf = PDF::loadView('pdfview');
return $pdf->download('pdfview.pdf', ['id'=>$id])->with('id', $id);
}
return view('pdfview', ['id'=>$id])->with('id', $id);
}
Route
Route::get('pdfview',array('as'=>'pdfview','uses'=>'MaatwebsiteDemoController#pdfview'));
View
Download PDF
I want to get the $employee->nip value
But it is still Undefined variable: id
Don't really have time to test it. But this thread looks promising.
https://laravel.io/forum/03-14-2016-basics-passing-info-from-one-view-to-another

Make a Laravel collection into angular array (octobercms)

I managed to fix a problem but I dont understand why it worked and it seems glitchy, so I wonder if someone could explain me. I wanted to get articles from my article models and retrieve that in angular, and I had a hard time getting the subkeys with "featured_images" from octobercms. I found a workaround, like this, in my laravel controller:
public function test()
{
$result = Article::take(4)->get();
$listarr = array();
foreach($result as $article) {
$listarr[] = $article;
foreach($article->featured_images as $image) {
}
}
return response()->json($listarr);
}
But if I remove the foreach($article->featured_images as $image) { } section I dont get the "featured_images" with $listarr. And just using $result doesnt give me those keys if i return response()->json($result);
This is how i want it: http://pastebin.com/MJvnbrrn
But not like this, without "featured_images": http://pastebin.com/1Xa3n9fD
And i get it how i want it if i do that forreach both on $result as $article and only if i then use foreach($article->featured_images as $image) { }. I think I am confused and that there is a more elegant way to this but multidimentional arrays is hard for me.
The foreach call is loading the relationship and therefore including it in the subsequent JSON data. The following call will preload the relationship, using eager loading, and should include it in the same way.
Article::with('featured_images')->take(4)->get();
Alternatively you can use "lazy eager loading"
$result = Article::take(4)->get();
$result->load('featured_images');

CakePHP - Declaration of Cart::read() should be compatible with Model::read

And then another message mostly the same saying
Declaration of Cart::save() should be compatible with Model::save
The basic problem is that the cart refuses to update whenever I try to add a product to it(its a simple ajax script).
I wish I could talk more about this but I have no clue whats wrong. I have tried passing different parameters into the function but nothing works. Here are the relevant fucntions, sorry it being long.
CartsController:
$carts = $this->Cart->read();
$products = array();
if (null!=$carts) {
foreach ($carts as $productId => $count) {
$product = $this->Product->read(null,$productId);
$product['Product']['count'] = $count;
$products[]=$product;
}
}
$this->set(compact('products'));
}
public function update() {
if ($this->request->is('post')) {
if (!empty($this->request->data)) {
$cart = array();
foreach ($this->request->data['Cart']['count'] as $index=>$count) {
if ($count>0) {
$productId = $this->request->data['Cart']['product_id'][$index];
$cart[$productId] = $count;
}
}
$this->Cart->save($cart);
}
}
$this->redirect(array('action'=>'view'));
}
Cart Model:
public function save($data) {
return CakeSession::write('cart',$data);
}
/*
* read cart data from session
*/
public function read($data) {
return CakeSession::read('cart', $data);
}
Thanks for any help.
This kind of question has now been asked a felt million times on Stackoverflow. Here is the basic workflow of how to deal with compiler errors and notices that will for sure help you to solve them all on your own:
Read error message
Think about it for a moment
Google for the error message
The error tells you that your method signature must match the inherited parents signature. The arguments must match.
As mark already has mentioned in a comment, overloading the core class methods should only be done if you're pretty sure that you know what you're doing. if not this is very likely ending up in a pile of fail.
You can disable the strict errors but this is really not recommended, they exist for a reason. See How to eliminate php5 Strict standards errors?
Looks like you're doing a cart, well, here is my gift for the CakePHP ecommerce developers: https://github.com/burzum/cakephp-cart-plugin

Trying to write a simple Joomla plugin

Please help, this is my first plugin I'm writing and I'm completely lost. I'm trying to write and update information in a table in a joomla database using my custom giveBadge() function. The functions receives two different variables, the first variable is the $userID and the second one is the digit 300 which I pass at the bottom of the class using giveBadge(300). At the same comparing the $userID in the Joomla database to ensure that the number 300 is given to the current user logged in the Joomla site.
Thanks in advance.
<?php
defined('JPATH_BASE') or die;
class plgUserBadge extends JPlugin
{
public function onUserLogin () {
$user =& JFactory::getUser();
$userID =& user->userID;
return $userID;
}
public function giveBadge ($userID, &$badgeID) {
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Fields to update.
$fields = array(
'profile_value=\'Updating custom message for user 1001.\'',
'ordering=2');
// Conditions for which records should be updated.
$conditions = array(
'user_id='.$userID,
'profile_key=\'custom.message\'');
$query->update($db->quoteName('#__user_badges'))->set($fields)->where($conditions);
$db->setQuery($query);
try {
$result = $db->query();
} catch (Exception $e) {
// Catch the error.
}es = array(1001, $db->quote('custom.message'), $db->quote('Inserting a record using insert()'), 1);
}
}
giveBadge(300); //attaches to $badgeID
?>
Here is not going well with your code:
You can drop the assign by reference in all your code (&) - you really don't need it, in 99% of the cases.
Use an IDE (for example Eclipse with PDT). At the top of your code you have & user->userID; Any IDE will spot your error and also other things in your code.
Study existing plugins to understand how they work. Here is also the documentation on plugins.
The method onUserLogin() will automatically be called by Joomla when the specific event is triggered (when your plugin is activated). Check with a die("My plugin was called") to see if your plugin is really called
inside onUserLogin() you do all your business logic. You are not supposed to return something, just return true. Right now your method does absolutely nothing. But you can call $this->giveBadge() to move the logic to another method.

CakePHP: User data saveAll silently fails?

I have a User model which hasMany Instrument and Genre. The Instrument and Genre save when I use the code below:
$this->User->saveAll($this->data, array(
'fieldList' => array('User', 'UserInstrument', 'Genre')))
)
But the User doesn't. All of the invalidFields arrays are empty in my debugger (User, UserInstrument, Genre, UserGenre, Instrument).
One weird thing I'm noticing, though, is that in here:
public function beforeSave() {
// get the password reset
if(isset($this->data[$this->alias]['password_reset'])) {
$this->data[$this->alias]['password'] = $this->data[$this->alias]['password_reset'];
unset($this->data[$this->alias]['password_reset']);
}
// get rid of the password confirm
if(isset($this->data[$this->alias]['password_confirm'])) {
unset($this->data[$this->alias]['password_confirm']);
}
// hash the password
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
I am unsetting the password_reset and password_confirm, but after the save is done, these fields magically appear back in $this->data['User'] (probably re-grabbed from $_POST). But if there was an error saving then the saveAll would return false. I have nothing in my error log either.
Any ideas as to why this is silently failing? Thanks!
if your purpose is to use hashing for newly created users, please consult this
Especially the beforeSave function which is simply just
public function beforeSave() {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
Please understand that in cakephp, if you include a field that is actually NOT in the datatable for the models, that field would be ignored. So you need not actually do an unset for your password_reset and password_confirm fields.
As for saving associated records and using fieldList, I noticed that you did not explicitly state the fields that you want to save in the fieldList key of the array.
Moreover, you stated that User hasMany Instrument and User hasMany Genre.
Please use the saveAssociated way.
Prepare your data like this in the controller:
$this->data['Instrument'] = array(
array('instrument_field1'=>'v1',
'instrument_field2' => 'v2',
),// first instrument
array('instrument_field1' => 'v1',
'instrument_field2' => 'v2')// second instrument
);
$this->data['Genre'] = array(
array('field1'=>'v1',
'field2' => 'v2',
),// first genre
array('field1' => 'v1',
'field2' => 'v2')// second genre
);
OR in your forms you do something like this:
$this->Form->input('Instrument.0.field1'); // for the first instrument
$this->Form->input('Instrument.1.field1'); // for the second instrument
Comment in my answer if I misunderstood the question.
I took out fieldList. Not the safest solution, but this was just causing more of a hassle than it was worth.

Resources