Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a property value inside JsonResponse Object in PHP or Laravel?

I'm doing a POST using Ajax and my Server is getting the data just fine. However, I'm struggling to access the value the user sent. In simple words how can I access the value of "user" (tom) ?. Anyone could get me on the right track please. Thank you in advance. Here's my JsonResponse object:

[2016-10-22 05:10:49] local.INFO: From Ajax: Illuminate\Http\JsonResponse Object
(
[data:protected] => {"user":"Tom","_token":"uRZJBVHH3worhjX4Ul6WlnJC1JYh3EVMNWob7Azr"}
[callback:protected] => 
[encodingOptions:protected] => 0
[headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object
    (
        [computedCacheControl:protected] => Array
            (
                [no-cache] => 1
            )

        [cookies:protected] => Array
            (
            )

        [headerNames:protected] => Array
            (
                [cache-control] => Cache-Control
                [content-type] => Content-Type
            )

        [headers:protected] => Array
            (
                [cache-control] => Array
                    (
                        [0] => no-cache
                    )

                [content-type] => Array
                    (
                        [0] => application/json
                    )

            )

        [cacheControl:protected] => Array
            (
            )

    )

[content:protected] =>     {"user":"Tom","_token":"uRZJBVHH3worhjX4Ul6WlnJC1JYh3EVMNWob7Azr"}
[version:protected] => 1.0
[statusCode:protected] => 200
[statusText:protected] => OK
[charset:protected] => 
)
like image 695
HenryDev Avatar asked Oct 22 '16 05:10

HenryDev


2 Answers

Using Laravel the data can also be accessed using illuminate getData() method.

$someVar->getData();

https://laravel.com/api/5.3/Illuminate/Http/JsonResponse.html#method_getData

like image 151
billi Avatar answered Oct 14 '22 13:10

billi


I solved my issue and I'm going to share it in case someone needs it. So the way I was getting the JsonObjec was by doing this in Routes.php:

Route::post('/register', function(){
if(Request::ajax()){
    Log::info('From Ajax: ' . print_r(Response::json(Request::all()), true));
    
    return var_dump(Response::json(Request::all()));
} 
});

But instead I did this to actually access the value of user (Tom).

$somevar = (Request::all());
Log::info('From Ajax: ' . print_r($somevar["user"], true));

This solve my issue. Hope it helps anyone out there!

like image 3
HenryDev Avatar answered Oct 14 '22 14:10

HenryDev