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

LaCoder's avatar

Dispatch event in page loads

Hello,

I have the below code, where the filter is applied, When I change filter dates, it sends dispatch pnlChartDataUpdated and then I get correct data in my chart and statistic component, where I am listening to this event.

But in this filter, I have defined fixed dates for which data need to load when component is loaded,

However it is not dispatching data to another component, so it shows blank or zero data.

How to dispatch data when the first page loads? It works fine if I change filter,

<?php

namespace App\Livewire\Journal;

use Livewire\Component;
use App\Models\DailyMtm;
use Livewire\Attributes\On;

class DashboardFilter extends Component
{    
    
    public $pnlChartData;
    public $startDate;
    public $endDate;

    public function __construct()
    {
        // Set default values if start date and end date are not provided
        $this->startDate = now()->subDays(30)->format('Y-m-d');
        $this->endDate = now()->format('Y-m-d');
    }

    #[On('journalDateFilterApplied')] 
    public function updateSelectedDate($startDate, $endDate)
    {
        $this->startDate = $startDate;
        $this->endDate = $endDate;
    }


    /**
     * Get the Profit and Loss (PnL) data based on the start and end dates, and dispatch an event with the updated data.
     */
    public function getPnLData()
    {
        $this->pnlChartData = DailyMtm::where('user_id', auth()->user()->id)->whereBetween('date', [$this->startDate, $this->endDate])->orderBy('date')->get();
        $this->dispatch('pnlChartDataUpdated', chartData:$this->pnlChartData);
    }

    public function render()
    {
        $this->getPnLData();
        return view('livewire.journal.dashboard-filter');
    }
}

0 likes
0 replies

Please or to participate in this conversation.