public function categoryCount()
{
$data = VisitorLog::select(
DB::raw("COALESCE(page_name, 'Undefined / Null Category') as category"),
DB::raw("COUNT(*) as total")
)
->where('page_type', 'category')
->groupBy('category')
->get();
return response()->json([
'status' => true,
'message' => 'Category wise visitor count',
'data' => $data
], 200);
}
React
import React, { useEffect, useState } from "react";
const baseURL = import.meta.env.VITE_API_BASE_URL;
export default function CategoryCount() {
const [categories, setCategories] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function loadCategoryCount() {
try {
const response = await fetch(`${baseURL}/api/visitor/category-count`);
const result = await response.json();
setCategories(result.data);
} catch (error) {
console.error("Failed to fetch category count:", error);
} finally {
setLoading(false);
}
}
loadCategoryCount();
}, []);
return (
<div className="p-4 border rounded">
<h2 className="text-lg font-bold mb-3">Category Wise Visitors</h2>
{loading ? (
<p>Loading...</p>
) : categories.length === 0 ? (
<p>No category data.</p>
) : (
<table className="w-full border">
<thead>
<tr className="bg-gray-200">
<th className="border p-2 text-left">Category</th>
<th className="border p-2 text-center">Visitors</th>
</tr>
</thead>
<tbody>
{categories.map((item, index) => (
<tr key={index}>
<td className="border p-2">{item.category}</td>
<td className="border p-2 text-center">{item.total}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
0 Comments