So not null?
$data = CollectionModel::with('items', function($q){
$q->where('release_at', '<', Carbon::now())->whereNotNull('release_at');
})->where('name', $this->name)->first();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi,
I have a collection which has many collection_items.
class Collection extends Model
{
public function items()
{
return $this->hasMany(CollectionItem::class)->orderBy('position');
}
}
class CollectionItem extends Model
{
public function collections()
{
return $this->belongsTo(Collection::class);
}
}
On the collection_item table I have a field called release_at which is a date time field.
If the release_at field is set, I would like to ensure that only collection_items which are retrieved are the ones which have the release_at set to be before today. I have been playing about with the below code but cannot get it to work correctly. Note release_at will not always be set; so only want to check them if they have been populated
$data = CollectionModel::with('items', function($q){
$q->where('release_at', '<', Carbon::now());
})->where('name', $this->name)->first();
Could anyone assist me with this?
Thanks
MoFish
@MoFish sounds like you want to check them seperately
public function items()
{
return $this->hasMany(CollectionItem::class)
->where(function ($query) {
$query->where('release_at', '<=', Carbon::now())->orWhereNull('release_at');
})->where(function ($query) {
$query->where('expire_at', '>=', Carbon::now())->orWhereNull('expire_at');
});
}
Please or to participate in this conversation.