Home > Software design >  How to refresh data without reloading page in laravel 8
How to refresh data without reloading page in laravel 8

Time:11-29

i want to make a live activities feed section for my website. I want to refresh the activities data without reloading the whole page. How to do this?

This is my code in controller

public function index()
{  
        $activities = collect();

        $attendance = $this->database->getReference($this->tableAttendance)->getValue();

        foreach($attendance as $key => $item){
            $activities->push(['name' => $item['name'] , 'date' => $item['date'], 'type' => $item['actionType'], 'time' => $item['time'],
            'latitude' => $item['latitude'], 'longitude' => $item['longitude']]);
        }

        $visit = $this->database->getReference($this->tableVisit)->getValue();

        foreach($visit as $key => $item){
            if(isset($item['sales'])){
                if(!$item['checkOutTime'] == ""){
                    $activities->push(['name' => $item['sales'], 'date' => $item['visitDate'], 'type' => 'Visited '.$item['customer'], 'time' => $item['checkOutTime'],
                'latitude' => $item['latitude'], 'longitude' => $item['longitude']]);
                }
            }
        }
        
        $activities = $activities->sortBy([
            ['date', 'asc'],
            ['time', 'desc'],   
        ]);
        return view('index', compact('activities'));
    
}

And this is my code in views

<div  style="padding: 0;">
    <div  id="activity-feed">
        @php $i = 1; @endphp
        @foreach ($activities as $key => $item)
            <a href="javascript:triggerClick({{$i  }})" >
                <div >
                    <h5 >{{$item['name']}}</h5>
                    <small>{{$item['date']}}</small>
                </div>
                <div >
                    @if($item['type'] == "checkout")
                        <p >Check Out</p>
                    @elseif($item['type'] == "checkin")
                        <p >Check In</p>
                    @else
                        <p >{{$item['type']}}</p>
                    @endif
    
                    <small>{{$item['time']}}</small>
                </div>
            </a>
        @endforeach  
    </div>
</div>

Thank you for your help :)

CodePudding user response:

You could make a javascript function that makes AJAX requests every X seconds to your backend/API to fetch data and then update your view.

Like:

function refreshData() {
    return new Promise((resolve, reject) => {
        fetch(endpoint)
        .then(res => res.json())
        .then(data => resolve(data))
        .catch(error => reject(error));
    })
}

setInterval(() => {
    refreshData.then(data => {
        // Update you view with data
    })
}, 60 * 1000); // 60 * 1000 milsec
  • Related