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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器