2
votes

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
@foreach($users as $user) then {{ $user->name }}Yeeooow

1 Answers

5
votes

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