doudan1123
2018-03-06 18:47
浏览 101
已采纳

我怎样才能在laravel模型中迭代属性?

I have a Laravel model with many attributes. So, I need iterate over these attributes. How can I do this? Something like this:

@foreach($model->attributes as $attribute)
// use $attribute
@endforeach

is it possible?

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

我有一个具有许多属性的Laravel模型。 所以,我需要迭代这些属性。 我该怎么做? 这样的事情:

  @foreach($ model-> properties as $ attribute)
 //使用$ attribute 
 @ endforeach \  n   
 
 

有可能吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongtao9095 2018-03-06 18:51
    已采纳

    If you have an object, use getAttributes():

    @foreach($model->getAttributes() as $key => $value)
        // use $attribute
    @endforeach
    
    已采纳该答案
    打赏 评论
  • dongshai2022 2018-03-06 18:52

    If these attributes were returned from a query, you can access the Model class directly:

    E.g.

    @foreach (User::all() as $user)
        <p>This is user {{ $user->id }}</p>
    @endforeach
    

    or, you can access the model reference given to a template:

    E.g.

    @foreach ($user->permissions as $permission)
        <p>This is an user permission {{ $permission->id }}</p>
    @endforeach
    

    See more in the Laravel Docs

    打赏 评论

相关推荐 更多相似问题