Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Deekshith's avatar

Avoid repeating same query in all controller functions

Hello All,

i have controller where in every function i have a query to check if passing course id is valid or not like below,

public function index($id)
{
	$coursedetail = Course::find($id);
	//if coursedetail is not empty then conitinue to next code logic
}

public function show($id)
{
	$coursedetail = Course::find($id);
	//if coursedetail is not empty then continue to next code logic
}

instead of writing course find query in every function. how to make it as reusable code? middleware is possible but apart from that any other method?

Thank you

0 likes
3 replies
Tray2's avatar
Tray2
Best Answer
Level 73

I don't know what you are after but, I don't see the need to check that.

I'm guessing that you want to fetch something that belongs to the course that you pass the id for?

You can use route model binding like this

public function index(Course $course)
{
	return view(lessons.index)->with([
			'course' => $course
			'lessons' => $course->lessons
	]);
}

Or you can just query with the course id.

public function index($courseId)
{
	return view('lessons.index')->with([
		'lessons' => Lesson::where('course_id', $courseId)->get() 
 	]);
}

The show method I guess is showing a single lesson, if so there is no need to see if it belongs to a course. The lesson either exist or it doesn't.

If you want to make 100% sure that the lesson belongs to the course you can

public function show($courseId, $lessonId)
{
	return view('lessons.show')->with([
		'lesson' => Lesson::where('course_id', $courseId)
				->where('id', $lessonId)->get() 
 	]);
}
2 likes
MohamedTammam's avatar

In that particular case, you don't need to do it that. You can just use Route Model Binding.

public function index(Course $course)
{
	// Do your stuff
}

Make sure that the parameters in the route is named course too

https://laravel.com/docs/9.x/routing#route-model-binding

But for other cases, for repeated part of the code, you can a can create a class and add your repeated code as method that you can call later.

1 like

Please or to participate in this conversation.