Skip to main content
1 of 4

Laravel, function on model or controller?

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?

Actually 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?

Thanks!