@jeffreyway @oussamamater Perhaps some more help around a concrete example.
I have this code in a controller and I need to retrieve the list of the sessions inside the Inertia::render() method. I already found that the code became heavy, so I decided to put it in another method, the list() method.
Typically could the list() method be in a service ? According to the video, I would say no, because this method doesn't do anything else than retrieving data from a query. But another answer could be yes, because the code in the controller would be cleaner.
Thanks for your help.
class SessionController extends Controller
{
public function index(Request $request, DateTimeService $datetimeService)
{
return Inertia::render('Sessions/Index', [
'sessions' => fn () => $this->list($request),
'years' => fn () => $datetimeService->getYears(),
'students' => fn () => StudentResource::collection(Student::
withCount('sessions')
->with('funding')
->with('path')
->with('project')
->orderBy('firstname')
->orderBy('lastname')
->where('active', true)
->get()
),
'types' => fn () => TypeResource::collection(Type::
withCount('sessions')
->orderBy('name')
->get()
),
'levels' => fn () => LevelResource::collection(Level::
withCount('sessions')
->orderBy('name')
->get()
),
'states' => fn () => StateResource::collection(State::
withCount('sessions')
->orderBy('name')
->get()
),
]);
}
public function list(Request $request)
{
$now = Carbon::now();
$year = isset($request->year) ? $request->year : $now->year;
$month = isset($request->month) ? $request->month : $now->month;
$studentId = isset($request->studentId) ? $request->studentId : null;
$typeId = isset($request->typeId) ? $request->typeId : null;
$levelId = isset($request->levelId) ? $request->levelId : null;
$stateId = isset($request->stateId) ? $request->stateId : null;
$sessions = Session::
with('student')
->with('funding')
->with('path')
->with('project')
->with('level')
->with('type')
->with('state')
->when($studentId, function($query) use ($studentId) {
$query->where('student_id', $studentId);
})
->when($typeId, function($query) use ($typeId) {
$query->where('type_id', $typeId);
})
->when($levelId, function($query) use ($levelId) {
$query->where('level_id', $levelId);
})
->when($stateId, function($query) use ($stateId) {
$query->where('state_id', $stateId);
})
->when($year > 0, function($query) use ($year) {
$query->whereRaw('year(date) = ?', [$year]);
})
->when($month > 0, function($query) use ($month) {
$query->whereRaw('month(date) = ?', [$month]);
})
->orderByDesc('date')
->get();
return $sessions;
}
...