首页 > 解决方案 > How to Apply IF Where Condition in Laravel Collation

问题描述

I need to collect my ticket sections from the array event, and my condition is

if 'custom_times' == 'yes' 

then pick up ticket section with only section_end_time < current date

Sample array Format

 {"event_id":1,"ticket_type":"event", "custom_times":"yes",.....,"ticket_section":[{"section_id":1,"section_end_time":"2019-10-10 12:12:12",..... }]}

Query

$ticket_sections = collect($event->ticket_sections)->map(function($sections) {
return $sections;
})->where('ticket_type', 'event')
  ->where('hide_online', 'no')
  ->when('custom_times' == 'yes', function($query){
     return $query->where('section_end_time', '<' ,$event->current_date_time);
  });

But the above query not return the actual result.

Thanks

标签: laravelcollectlaravel-6

解决方案


我认为您将集合与查询生成器混淆了。

集合的when方法需要一个布尔值才能工作,并且不能与集合成员上的条件一起工作。

以下是您可以执行所需操作的方法:

$ticket_sections = collect($event->ticket_sections)
  ->where('ticket_type', 'event')
  ->where('hide_online', 'no')
  ->filter(function($section) use ($event) {
     return $section->custom_times !== 'yes' 
          || $section->section_end_time < $event->current_date_time;
  });

推荐阅读