0

Is it possible to call function from model into the controller in foreach loop?

This is my model

class Order extends Eloquent
{
    public static function getData($data)
    {
        // function code 
    }
}

This is what I'm trying in my controller

$get = Order::all();
foreach ($get->getData($get->details) as $itemId => $details) {
    dd($details);
}

This produce error

Error: Call to undefined method Illuminate\Database\Eloquent\Collection::getData()

I've tried exact same code in my blade and there is working without any issue.

So, how I'm suppose to call and use the function in my controller?

1 Answer 1

3

The getData() function is declared as static in your class

public static function getData($data)
{
    // function code 
}

So it should be called using class name as Order::getData($get->details)

foreach (Order::getData($get->details) as $itemId => $details) {
    dd($details);
}
Sign up to request clarification or add additional context in comments.

5 Comments

It's return ErrorException: Undefined property: Illuminate\Database\Eloquent\Collection::$details
check what you are getting in $get variable
I'm getting all data as object(Illuminate\Database\Eloquent\Collection)#522 (1) ....
And if is matter details holds data as array?
It turn out that I need to json_decode it first. Thanks for the help

Your Answer

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