Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering Laravel eloquent collections with filter method

  $events=Event::all();
  if (isset($scheduling) && $scheduling!=="All")
  {
     $events = $events->filter(function($event) use ($scheduling)
     {
        return $event->where('scheduling',$scheduling);
      });
   }
  $events=$events->get();

can some one correct this code. the inner filter is not working. the results are same with or without applying filters. i need to apply lot filters like this basing on conditions

like image 546
lch Avatar asked Jul 27 '15 15:07

lch


People also ask

What does filter do in laravel?

The filter query parameters can be used to add where clauses to your Eloquent query. Out of the box we support filtering results by partial attribute value, exact attribute value or even if an attribute value exists in a given array of values. For anything more advanced, custom filters can be used.

What is the use of pluck in laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.


1 Answers

You don't have to use where condition in it, you can just return true or false from within callback, depending on the selection condition.

Below code will keep only those eventsthat pass a given truth test:

   $events=Event::all();

   if (isset($scheduling) && $scheduling!=="All") 
   {  
      $events = $events->filter(function($event) use ($scheduling)
      {
         return $event->scheduling == $scheduling;
       });
    }

   dd($events); //Collection

Read More

like image 65
pinkal vansia Avatar answered Oct 09 '22 16:10

pinkal vansia