0

I am trying to select the last element from some JSON data but am getting an "Undefined Method" return. My code is to get the $order_serialized data from a specific Order and then to pick the $last_item in that JSON data and plug it into a dd() just for testing right now. If anyone could point out or explain where I went wrong it would be very much appreciated! Thank you so very much!

Controller:

public function getEdit($id){
    $order = Order::where('id', '=', $id);

    if($order->count()) {
        $order          = $order->first();
        $order_serialized   = json_decode($order->order_serialized);
        $last_item          = $order_serialized->last();


                    dd($last_item);


        foreach($order->order_serialized as $key => $value){
            $order->$key = $value;
        }
        return View::make('orders.edit')
                ->with('order', $order);
                /*->with('last_item', $last_item);*/
    }   else {
        return App::abort(404);
    }
}
2
  • 1
    Which line are you getting the 'undefined method' error? Commented Mar 25, 2014 at 15:37
  • I am getting " undefined method stdClass::last() " on line 101. Commented Mar 25, 2014 at 16:13

2 Answers 2

1

When you do

$order_serialized = json_decode($order->order_serialized);

You get back a standard class object, so it doesn't have any last() method.

I would do this instead:

$order_serialized   = json_decode($order->order_serialized, true);
$last_item = array_pop($order_serialized);

Sending true as the second param to json_decode will give you an array instead of an object.

Sign up to request clarification or add additional context in comments.

Comments

1

json_decode is going to return a stdClass object which does not have any methods, so calling $order_serialized->last() is giving you the "undefined method" error. In order to call the last method on some class, you're going to have to instantiate that class. I don't know of a way to decode JSON to a specific class in PHP.

1 Comment

Thank you for explaining where I went wrong. Knowing what the problem is is a great place to start fixing it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.