How to do search filtering through a collection of arrays?

83 Views Asked by At

I am going to build advance search function in laravel 5. I queried from 'itemregistrations' table by filtering a few fields such as negeriID, categoryID and operasiID. I need to do array map to calculate age value of each item and put in the array. By getting values using itemregistration table and calculating age runs okay but it problem in searching through the if statement. It cannot searching and retrieve the values through the array in the collection.

   $newitem = DB::table('itemregistrations')
        ->select('itemregistrations.*')
        ->get();

    //added code to get 'age' value:
    $newitem->map(function ($detail) {

        $detail->age = \Carbon\Carbon::createFromFormat('Y',$detail->lahir_yy)->diffInYears(); 
        return $detail;
    });   


    if ($request->has('negeri_lahir')) {
        $newitem->where('NegeriID', '==', $request->negeri_lahir);
    }

    if ($request->has('kategori')) {
        $newitem->where('CategoryID', $request->kategori);
    }

    if ($request->has('pangkat')) {
        $newitem->where('OperasiID', $request->pangkat);
    }

   dd($newitem->get()); 

The problem because of the array map added, turning the collection in array values causing this error. It is producing error:

 Type error: Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in C:\xampp\htdocs\

This is the array list in the collection for dd($newitem);

 #items: array:1123 [▼
0 => {#709 ▶}
1 => {#680 ▶}
2 => {#681 ▶}
3 => {#712 ▶}

Collection {#671 ▼
#items: array:1123 [▼
0 => {#709 ▼
  +"ItemRegistrationID": 1
  +"COID": 109064
  +"FType": ""
  +"STNo": "0"
  +"RegistrationDate": "2005-12-01"
  and more attributes...

How to enable the searching through the array list?

1

There are 1 best solutions below

10
On BEST ANSWER
  1. First of all, you don't need to use select() in query.
  2. Looks like better to make filtering in db query using when().

Try:

$newitem = DB::table('itemregistrations')
    ->when(request('age'), function($query){
        $query->whereRaw('YEAR(curdate()) - lahir_yy >= ?', [request('age')]);
    })
    ->when(request('negeri_lahir'), function($query){
        $query->where('NegeriID', request('negeri_lahir'));
    })
    ->when(request('kategori'), function($query){
        $query->where('CategoryID', request('kategori'));
    })
    ->when(request('pangkat'), function($query){
        $query->where('OperasiID', request('pangkat'));
    })
    ->get();