dpi9530 2017-02-28 21:27
浏览 117
已采纳

未定义属性:Illuminate \ Database \ Eloquent \ Collection :: $ name Laravel 5.3

The Route is Route::resource('/admin/post', 'postController');

in controller the code is

public function index()
{
    $s = Singer::where('id','<',5)->get()->name;

    return view("admin.new-post", ['s'=>$s]);
}

And the view is

<select class="form-control select2 select2-hidden-accessible" multiple="" data-placeholder="Select a State" style="width: 100%;" tabindex="-1" aria-hidden="true">

                                <?php foreach ($s as $ss){
                                    echo '<option>'. $ss .'</option>';
                                 }?>

                            </select>

I want to list down all the names of singers from data base in select. And the problem is that when I get a single value using first() in query instead of get() it returns single value correctly widhout any error. but when I use get() and in view use foreach loop to get all singers then it gives this error. Undefined property: Illuminate\Database\Eloquent\Collection::$name. I have reviewed code many times but could not understand that what the error is. while there is no problem to get a single name.. please provide me some solution.

  • 写回答

1条回答 默认 最新

  • dph19153 2017-02-28 21:36
    关注

    Controller Code

    public function index()
    {
    $s = Singer::where('id','<',5)->get();
    
    return view("admin.new-post", ['s'=>$s]);
    }
    

    View Code

    <select class="form-control select2 select2-hidden-accessible" multiple="" data-placeholder="Select a State" style="width: 100%;" tabindex="-1" aria-hidden="true">
    
                                <?php foreach ($s as $ss){
                                    echo '<option>'. $ss->name .'</option>';
                                 }?>
    
                            </select>
    

    When you use first() you get a single result, when you use get() you are getting a collection of results, even if your searching for one user.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 hexo+github部署博客
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?