doumi5223
2017-07-19 13:27
采纳率: 100%
浏览 149
已采纳

在Laravel中将模型中的函数调用到控制器中

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?

图片转代码服务由CSDN问答提供 功能建议

是否可以在foreach循环中将函数从模型调用到控制器中?

这是我的模型

  class Order extends Eloquent 
 {
 public static function getData($ data)
 {\  n //功能代码
} 
} 
   
 
 

这是我在控制器中尝试的内容

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

此产生错误

错误:调用未定义的方法Illuminate \ Database \ Eloquent \ Collection: :getData()

我在我的刀片上尝试了完全相同的代码,并且没有任何问题。

那么,我想如何在我的控制器中调用和使用该函数?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongtuoleng8624 2017-07-19 13:30
    已采纳

    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);
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题