Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shariff's avatar
Level 51

One to many relationship not working with whereHas condition

Hi

I have one-to-many relationship where one payment mode has many transaction. I want to filter transaction based on dates. So I tried with this query. But I 'm getting all the transaction. It's not getting filtered based on the dates. I don't know what is wrong in my code.

public function index()
    {
        $from_date = request()->from_date;
        $to_date  = request()->to_date;

		$query = MstPayMode::with('bills');
        $query->whereHas('bills', function ($q) use ($from_date, $to_date) {
                $q->whereDate('bill_date', '>=', $from_date)
                    ->whereDate('bill_date', '<=', $to_date);
            });

        $bills = $query
            ->get();
        return view('admin.reports.bill-wise', compact('bills'));
    }

Payment model

class MstPayMode extends Model
{
    protected $table = 'mst_pay_mode';
    protected $primaryKey = 'sk_payment_mode_id';
  
    public function bills()
    {
        return $this->hasMany(Bill::class, 'mst_pay_mode_id', 'sk_payment_mode_id');
    }
}

Transaction model

class Bill extends Model
{
    protected $table = 'bill_bill_main';
    protected $primaryKey = 'bill_id';
    public $timestamps = false;

    public function payment_mode()
    {
        return $this->belongsTo(MstPayMode::class);
    }
}

Thank you

0 likes
6 replies
Sinnbeck's avatar

You say that you are getting all transactions, but the code only handles payment methods and bills?

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Do you mean you want to limit with() as well?

		$bills = MstPayMode::query()
            ->withWhereHas('bills', function ($q) use ($from_date, $to_date) {
                $q->whereDate('bill_date', '>=', $from_date)
                    ->whereDate('bill_date', '<=', $to_date);
            })->get();
shariff's avatar
Level 51

@Sinnbeck @sinnbeck Thank so much it is working now. That means we cannot call with seperately? while filtering the records? we should use withWhereHas?

Sinnbeck's avatar

@shariff with() isn't filtered if you do it seperately. It only filters the main query. I suggest installing debugbar and check the queries being run

1 like

Please or to participate in this conversation.