Laravel 5 – Use multiple where clauses in your collection

Laravel 5.1

Right now I am working on a project with Laravel 5.1. I’ve a situation here where I need to fetch all receipts from databased based on Start and End time of Breakfast, Lunch and Dinner. I could easily do it by three separate query to database and stored them in three variables but here I can reduct the hit to database server and use the collection functions.

I’ve first fetch all the receipts of a given date

$receipts	= Receipts::where(function($query) use ($report_date){
		$query->where(function($query) use ($report_date){
			     $query->where('date', '=', $report_date);
			$query->where('type', '=', 'restaurant');
				$query->orWhere('type', '=', 'takeaway');

Now I have all receipts of a single day but I want to slice the receipts for breakfast, lunch and dinner receipts with the help of Laravel collection. I didn’t know how to use multiple filters in a single collection and founding nothing after searching google and stackoverflow. Then I started using common sense and it worked like a charm.

Multiple Where clauses in a single Collection Object

Here I need to give breakfast_start and breakfast_end time and it will filter with create_date property of the object. Anything in between, it will return the breakfast receipts .

$breakfast = $receipts->filter(function($item) use($breakfast_start){
		    return $item->create_date >= $breakfast_start;
		->filter(function($item) use($breakfast_end){
		    return $item->create_date <= $breakfast_end;

The code worked perfectly and I thought I should share the code snippet which might be helpful for someone like me.

Author: Ariful Haque

Software Engineer | Freelance Web Application Developer PHP, CodeIgniter, WordPress, JavaScript, jQuery, Ajax, Ubuntu, CentOS, Apache..

Leave a Reply

Your email address will not be published. Required fields are marked *