david001's avatar

Filter data with Laravel

I need help in searching data with laravel i have a form with field date from,to and district input field

My form in view

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-12">


<div class="container">
  <div class="panel panel-heading">All Registered Cases({{ $cases->count() }})
    <form action="/cases" method="GET">
    From:<input type="date" name="from">
    To:<input type="date" name="to">
    District:<input type="text" name="district" class="">
    <button type="submit" class="btn btn-success btn-sm">Search</button>
  </form>

  </div>
 

<div  class="panel panel-body">
  <table class="table table-striped">
    <thead>
      <tr>
        <th>Token</th>
        <th>Full name</th>
        <th>Email</th>
        <th>Address</th>
        <th>View</th>
      </tr>
    </thead>
    <tbody>
      @if($cases->count())
        @foreach($cases as $case)
        <tr>
          <td>{{ $case->token }}</td>
          <td>{{ $case->full_name }}</td>
          <td>{{ $case->email }}</td>
          <td>{{ $case->district }}</td>
          <td><a href="{{ route('cases.show',[$case->id]) }}">Browse</a></td>
        </tr>
        @endforeach
      
      @else
        <td><b>No record found.</b></td>
      @endif
    </tbody>
  </table>
     {{--  {{ $cases->links() }} --}}
     
     {!! $cases->appends(Request::only(['from'=>'from', 'to'=>'to','district'=>'district']))->render() !!}

</div>


    </div>
  </div>
</div>
@endsection

Route: Route::get('cases','CaseRegisterController@index');

CaseRepositories.php

public function allCases()
    {
        return Case::paginate(40);
    }

    public function searchCases(array $searchData)
    {
        $from = $searchData['from'];
        $to = $searchData['to'];
        $district = $searchData['district'];
  
         //Logic if all fields are given

        if(!empty($district)&&!empty($from)&&!empty($to)){
        $cases = Case::whereDate('created_at','>=',$from)
                        ->whereDate('created_at','<=',$to)

                        ->where('district',$district)
                        ->paginate(1);
                        return $cases;
        }else{
      //Logic if from and to  fields are given but district not given

        $cases = Case::whereDate('created_at','>=',$from)
                        ->whereDate('created_at','<=',$to)
                       // ->where('district',$district)
                        ->paginate(1);  
                        return $cases;
        }
        
    }

Controller:

public function index(Request $request)
    {
        if($request->get('from')||$request->get('to')||$request->get('district')){
            $cases = $this->case->searchCases($request->all());
          // dd($cases);
                   return view('case.index',compact('cases'));

       }

        $cases = $this->case->allCases();
        return view('case.index',compact('cases'));
    }



I have two problem: First: How can i modify code in CaseRepositories.php and Controller.I want to write better logic if possible

Second: when all fields are not empty ie:from,to and districtare provided pagination works fine

{!! $cases->appends(Request::only(['from'=>'from', 'to'=>'to','district'=>'district']))->render() !!}

but Admin can filter data with only from and to date makingdistrict field empty.In such case pagination won't work.it gives error like this: Undefined index: district.How can i handle this error

0 likes
2 replies
lostdreamer_nl's avatar
Level 53

ok, a few first steps to writing better code:

public function searchCases(array $searchData)
    {
        $from = $searchData['from'];
        $to = $searchData['to'];
        $district = $searchData['district'];
    [...]
    }

What is happening here is: You created a method (searchCases) that accepts an array of data, but you have to read through the whole method to see which keys are needed in this array.... This is going to bite you later (as you see now with the Undefined index: distinct).

Reformat that method into:

public function searchCases($from, $to, $district = NULL) 
{
    [...]
}

Now you instantly see that the method needs a $from and $to and has an optional $district parameter and we can remove the first 3 lines of the method which try to extract that data from the array (without even checking if the keys existed in the first place, giving you that undefined index error)

Now for the actual code:

public function searchCases($from, $to, $district = NULL) 
{
    $cases = Case::whereDate('created_at', '>=', $from)
                        ->whereDate('created_at', '<=', $to);
    if($district) {
        $cases = $cases->where('district',$district);
    }
    return $cases->paginate(1);
}

We start building a new query, based only on the $from and $to dates. If a district was given, we'll apply that as well.

And we return the paginated results.

Using the repository would now be a matter of:

$cases = $this->case->searchCases($request->get('from'), $request->get('to'), $request->get('district'));
2 likes

Please or to participate in this conversation.