# Method on Laravel model to find courses related to a course

I have a Laravel project that has courses. I want to take the related courses from one.

Should I create the method in the model (the php class) or in the controller?

Currently I have this code in the model:

class Course extends Model {

public function relatedCourses() {

$all_courses = new Collection; // Similar name$words = explode($this->name, " "); foreach ($words as $word) {$courses = Course::where(function($query) use ($word) {
$query->where('id', '<>',$this->id)->where('name_es', 'LIKE', "%$word%")->orWhere('name_cat', 'LIKE', "%$word%");
})->get();

$all_courses =$all_courses->merge($courses); } return$all_courses;
}

}


Should I move it to the controller?

No, this code belongs in the Model (or a related repository if you where using such a design, though thats kind of overkill with Active Record).

You can however reduce the number of queries by using the foreach loop to build a single query, instead of making a query per word:

public function relatedCourses()
{
$words = explode($this->name, " ");
return Course::where(function($query) use ($words) {
$query->where('id', '<>',$this->id);
foreach ($words as$key => $word) { if($key==0){
$query->where('name_es', 'LIKE', "%$word%")->orWhere('name_cat', 'LIKE', "%$word%"); }else{$query->orWhere('name_es', 'LIKE', "%$word%")->orWhere('name_cat', 'LIKE', "%$word%");
}
}
})->get();
}