Eirtaza
Eirtaza

Reputation: 147

Trying to get property of non-object in Laravel even when it is present

the data i am testing on is like this in feed variable

{
    "id": 32,
    "user_id": 1,
    "target_id": 3,
    "feedable_id": 7,
    "feedable_type": "review",
    "created_at": "2016-05-23 14:18:22",
    "updated_at": "2016-05-23 14:18:22",
    "feedable": {
        "id": 7,
        "user_id": 1,
        "slug_id": 3,
        "review": "y this product is so quite?",
        "stars": 9,
        "created_at": "2016-05-23 14:18:22",
        "updated_at": "2016-05-23 14:18:22",
        "slug": {
            "id": 3,
            "value": "Quite",
            "views": 5,
            "user_id": 1,
            "category_id": 1,
            "created_at": "2016-05-23 14:18:03",
            "updated_at": "2016-05-24 12:47:29"
        }
    }
}

but i am not be able to access the value:quite in my view

{{ $feed->feedable->slug->value }}

Laravel throws

Trying to get property of non-object (View: ...

Upvotes: 0

Views: 39

Answers (1)

Murad Hasan
Murad Hasan

Reputation: 9583

This is a json variable so you need to decode it first then access the value. Using json_decode you can decode the variable and get the desire value.

Check online.

$json = '{
    "id": 32,
    "user_id": 1,
    "target_id": 3,
    "feedable_id": 7,
    "feedable_type": "review",
    "created_at": "2016-05-23 14:18:22",
    "updated_at": "2016-05-23 14:18:22",
    "feedable": {
        "id": 7,
        "user_id": 1,
        "slug_id": 3,
        "review": "y this product is so quite?",
        "stars": 9,
        "created_at": "2016-05-23 14:18:22",
        "updated_at": "2016-05-23 14:18:22",
        "slug": {
            "id": 3,
            "value": "Quite",
            "views": 5,
            "user_id": 1,
            "category_id": 1,
            "created_at": "2016-05-23 14:18:03",
            "updated_at": "2016-05-24 12:47:29"
        }
    }
}';
$feed = json_decode ($json);

echo $feed->feedable->slug->value; //Quite

Upvotes: 1

Related Questions