File: /var/www/console.fixgini.com/app/Http/Controllers/Admin/UserController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Models\User;
use Illuminate\Http\Request;
use Livewire\WithPagination;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
use WithPagination;
public function search(Request $request)
{
try {
// Validate the incoming request
$validatedData = $request->validate([
'role' => 'sometimes|exists:users,role',
'status' => 'sometimes|exists:users,status',
]);
// Start a query on the User model
$query = User::query();
// Apply filters if they are present
if (!empty($validatedData['role'])) {
$query->where('role', $validatedData['role']);
}
if (!empty($validatedData['status'])) {
$query->where('status', $validatedData['status']);
}
// Get the results with pagination
$users = $query->with('wallet')->latest()->paginate(10);
// dd($users);
// Return the successful response
return response()->json([
'status' => 'success',
'data' => $users
], 200);
} catch (\Exception $e) {
// Return an error response
info($e->getMessage());
return response()->json([
'status' => $e->getMessage(),
'message' => 'You are not authorised'
], 400);
}
}
public function count()
{
try {
// Count total users and users by role
$totalUsers = User::count();
$buyerCount = User::where('role', 'buyer')->count();
$sellerCount = User::where('role', 'seller')->count();
$adminCount = User::where('role', 'admin')->count();
// Return a successful response with the user counts
return response()->json([
'status' => 'success',
'data' => [
'total_users' => $totalUsers,
'buyers' => $buyerCount,
'sellers' => $sellerCount,
'admins' => $adminCount
],
'message' => 'User count fetched successfully'
], 200);
} catch (\Throwable $e) {
// Log the error message
Log::error('Error fetching user count: ' . $e->getMessage());
// Return an error response
return response()->json([
'status' => 'error',
'message' => 'An error occurred while fetching user counts.',
'error' => $e->getMessage()
], 500);
}
}
}