Yamato
4 months ago

How can I do a laravel filter that accepts two inputs or just one

Posted 4 months ago by Yamato

So, i have a database with students, and i have, names, group name of students, and something like that, I want to make a filter system, with multiple filter, for example i want to display row (of table) with Students with name John and are in group A (both conditions must be). But the problem is when i want a filter only for students, for example i don't need a particular group, my script doesn't work, only for two filters, no only one.

I tried this:

in route: Route::post('/search', '[email protected]')->name('search'); in HomeController:

public function search(Request $request)
{
     $students = Student::query();
     $datas = $request->all();
    

    if ($request->has('group')) {
        $students = $students->where('group', $request->group);
    }

    if ($request->has('name')) {
        $students = $students->where('name', $request->name);
    }
    
    $students = $students->paginate(40);
    $data = array (
        'students' => $students,
        'datas' => $datas,
    );
    return view('searchStudent')->with($data);
}

And in blade, two simple inputs, button, and the table with students.

<div class="col-sm-4">
   <div class="search-box grey lighten-3">
      <h2>Search Students</h2>
      <div class="input-r">
         <form action="{{ route('search') }}" method="post">
            @csrf
            <input name="name" type="text" class="form-control">
            <input name="group" type="text" class="form-control">
            <button class="btn btn-info btn-block" type="submit">Search</button>
         </form>
      </div>
   </div>
</div>
<div class="col-sm-8">
   @foreach ($students as $student)
   <div class="row pb-5">
      <div class="col-md-4">
         <div class="profiel-img">
            <img src="{{ asset($student->image) }}" alt="thumbnail" class="img-thumbnail" style="width: 200px">
         </div>
         <a class="btn btn-primary btn-sm" style="font-size: 12px; margin-left: 40px;" href="{{ route('student.show', $student) }}">Visit Profile</a>
      </div>
      <div class="col-md-8 pb-3">
         <h3 class="black-text"> {{ $student->name }}</h3>
         <h3 class="black-text"> {{ $student->group }}</h3>
         <hr style="border-top:1px solid #ccc;">
      </div>
   </div>
   @endforeach
   {{ $students->appends($datas)->links() }}
</div>

I need to work for only name input, and filter, only for group, and for both input. With this code, it works only for both (i can't filter only name, only group, etc. )

Please sign in or create an account to participate in this conversation.