dpcyx08288 2018-06-08 11:54
浏览 120
已采纳

未定义属性:Illuminate \ Database \ MySqlConnection :: $ name

Hi i'm trying to make a small system filtering in laravel using the following function in my controller to filter users by their roles or their names here's my current code:

profilecontroller.php:

public function membrevis()
{
    $filter = isset($_GET['filter']) ? $_GET['filter'] : null;
    $users = DB::table('users')
        ->join('user_role', 'users.id', '=', 'user_role.user_id')
        ->join('roles', 'user_role.role_id', '=', 'roles.id')
        ->where('users.valid','=',0)
        ->select('users.*','roles.description');
   if ($filter != null) {
        $users->where('users.name','like','%'.$filter.'%')
            ->orWhere('roles.description',' like','%'.$filter.'%');
   }
   $users->get();

   return view('membre2',['users'=> $users]); 
}

My view has an input form where you can type the name or the role of the members you are trying to filter :

membre2.blade.php:

<form action="/profilecontroller/membrevis" method="get">
    <input type="text" name="filter" >
    <button type="submit">filter</button>
</form> 

@foreach($users as $users) 

   <h4 class="media-heading">{{ $users->name }}</h4>

@endforeach

The error i'm getting is Undefined property: Illuminate\Database\MySqlConnection::$name

I have no idea why i'm getting this error i'm obviously passing $users to my view with this line of command:

return view('membre2',['users'=> $users]);

Any help would be appreciated! thank you

展开全部

  • 写回答

1条回答 默认 最新

  • dongsheng8158 2018-06-08 12:06
    关注

    when using $users->get() it returns Collection instance, you must be assign $users = $users->get(); Corrected code is

        public function membrevis()
        {
            $filter = isset($_GET['filter']) ? $_GET['filter'] : null;
            // also can use this structure $filter = isset($_GET['filter']) ?? null;
            $users = DB::table('users')
                ->join('user_role', 'users.id', '=', 'user_role.user_id')
                ->join('roles', 'user_role.role_id', '=', 'roles.id')
                ->where('users.valid','=',0)
                ->select('users.*','roles.description');
            if ($filter != null) {
                $users->where('users.name','like','%'.$filter.'%')
                    ->orWhere('roles.description',' like','%'.$filter.'%');
            }
            $users = $users->get();
    
            return view('membre2',['users'=> $users]); 
        }
    

    also in blade fix it

    @foreach($users as $user) 
    
       <h4 class="media-heading">{{ $user->name }}</h4>
    
    @endforeach
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了