feat: request optimizations
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Video;
|
||||
use App\Models\Workshop;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (!$user) {
|
||||
return response()->json([
|
||||
'message' => 'Utilizador não autenticado',
|
||||
'data' => null,
|
||||
'errors' => null,
|
||||
], 404);
|
||||
}
|
||||
|
||||
$userId = $user->id;
|
||||
$role = $user->role_id;
|
||||
|
||||
|
||||
$videos = Video::select('id', 'title', 'thumbnail', 'is_active', 'order')
|
||||
->where('is_active', true)
|
||||
->whereDoesntHave('views', function ($q) use ($user) {
|
||||
$q->where('user_id', $user->id);
|
||||
})
|
||||
->orderBy('order', 'asc')
|
||||
->limit(3)
|
||||
->get()
|
||||
->map(function ($video) {
|
||||
return [
|
||||
'id' => $video->id,
|
||||
'title' => $video->title,
|
||||
'thumbnail' => $video->thumbnail,
|
||||
'is_active' => $video->is_active,
|
||||
'watched' => false,
|
||||
];
|
||||
});
|
||||
|
||||
$videosCount = Video::select('id')->where('is_active', true)->count();
|
||||
|
||||
$videosWatched = Video::select('id')
|
||||
->where('is_active', true)
|
||||
->whereHas('views', function ($query) use ($user) {
|
||||
$query->where('user_id', $user->id);
|
||||
})->count();
|
||||
|
||||
$workshops = Workshop::select(['id', 'title', 'image', 'date', 'time_start', 'time_end', 'status'])
|
||||
->with(['users:id'])
|
||||
->where('status', 'pending')
|
||||
->orderBy('date', 'asc')
|
||||
->orderBy('time_start', 'asc')
|
||||
->limit(3)
|
||||
->get()
|
||||
->map(function ($workshop) {
|
||||
return [
|
||||
'id' => $workshop->id,
|
||||
'title' => $workshop->title,
|
||||
'image' => $workshop->image,
|
||||
'date' => $workshop->date,
|
||||
'time_start' => $workshop->time_start,
|
||||
'time_end' => $workshop->time_end,
|
||||
'status' => $workshop->status,
|
||||
'users' => $workshop->users->pluck('id'),
|
||||
];
|
||||
});
|
||||
|
||||
$workshopsInscribed = Workshop::select('id')
|
||||
->where('status', 'pending')
|
||||
->whereHas('users', function ($query) use ($user) {
|
||||
$query->where('user_id', $user->id);
|
||||
})->count();
|
||||
|
||||
$workshopsCount = Workshop::select('id')->where('status', 'pending')->count();
|
||||
|
||||
return response()->json([
|
||||
'videos' => $videos,
|
||||
'videosWatched' => $videosWatched,
|
||||
'videosCount' => $videosCount,
|
||||
'workshops' => $workshops,
|
||||
'workshopsCount' => $workshopsCount,
|
||||
'workshopsInscribed' => $workshopsInscribed,
|
||||
'userId' => $userId,
|
||||
'role' => $role,
|
||||
], 200);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user