"true","token"=>$t...">

Returning json in laravel

I have a controller that returns a JSON string below

$response = Response::json(array("success"=>"true","token"=>$token));

      

return value {"success":"true","token":{}}

, but when I put in a static value like

$response = Response::json(array("success"=>"true","token"=>"12345"));

      

correct return value {"success":"true","token":"12345"}

The variable $token

is created because it is inserted into the database, but not returned as expected.

The token is generated from the UUID of the webpatser using: Uuid: generate ();

Question: How can I fix this?


UPD:

Results var_dump($token)

:

["string":protected]=> string(36) "d0c95650-3269-11e4-a55e-15cdb906eead"

      

UPD 2:

$response = Response::json(array("success"=>"true","token"=>$token[0]));

returns {"success":"true","token":NULL}

      

Tried changing the value of the $ token to other variables in such a way that

$test = "test";

      

then

$response = Response::json(array("success"=>"true","token"=>$test));

      

return {"success":"true","token":"test"}

+3


source to share


3 answers


Your variable $token

contains an object that has a value as an element protected

that the json encoder cannot access.

There should probably be a way to get it with some getter methods like $token->getValue()

or something similar. If so, you need to change your answer to

$response = Response::json(array("success"=>"true","token"=>$token->getValue()));

      

If you can provide the class methods get_class_methods()

, I can offer further suggestions.

As a workaround (not actually the preferred way), you can try using reflection :



<?php
header('Content-Type: text/plain; charset=utf-8');

class A {
    protected $test = 'xxx';

    public function change(){
        $this->test = 'yyy';
    }
}

$a = new A();
$a->change();

$class    = new ReflectionClass(get_class($a));
$property = $class->getProperty('test');

$property->setAccessible(true); // "Dark "magic"

echo $property->getValue($a); // "Dark magic"
?>

      

Shows:

yyy

      

So, in your code, it could be like this:

$class    = new ReflectionClass(get_class($token));
$property = $class->getProperty('string');

$property->setAccessible(true);

$token = $property->getValue($token);

$response = Response::json(array("success"=>"true","token"=>$token));

      

+2


source


You need to provide this with a getter method in the class itself.

So in the class:

public function getData()
{
  return $this->string;
}

      



And in your program:

$token->getData();

      

0


source


User foreach for $ token and get value from it. Assign it in some variable and use it in your answer.

ex.

$my_tocken = "";
foreach ($tocken as $real_tocken){
  $my_tocken = $real_tocken;
}

      

Now build your response as usual with test variables.

0


source







All Articles