n2fole00's avatar

No such table error

Hi, I'm getting the following error

SQLSTATE[HY000]: General error: 1 no such table: course_modules

For this method (error line is get() in $courseModules)

    public function edit(int $course_id): View
    {
        $course = Course::find($course_id); 

        $courseModules = CourseModule::where('course_id', '=', $course_id)
        ->join('modules', 'course_module.module_id', '=', 'modules.id')
        ->select('course_module.*', 'modules.name')
        ->get()
        ->toJson(); 

        $moduleIds = CourseModule::where('course_id', $course_id)->pluck('module_id');
        $modules = Module::where('user_id', Auth::user()->id)
            ->whereNotIn('id', $moduleIds)
            ->get()
            ->toJson(); 

        return view('admin.courses.create_edit_course', [
            'course' => $course, 'courseModules' => $courseModules, 'modules' => $modules
        ]);
    }

My migration (2024_03_02_203616_create_course_module_table.php) is

    public function up(): void
    {
        Schema::create('course_module', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('course_id');
            $table->unsignedBigInteger('module_id');
            $table->integer('sort')->default(1);
            $table->timestamps();
            $table->foreign('course_id')->references('id')->on('courses');
            $table->foreign('module_id')->references('id')->on('modules');
        });
    }

Why is it asking for the course_modules table when my table is course_module?

Thanks.

0 likes
2 replies
gych's avatar
gych
Best Answer
Level 29

You're getting this error because Laravel expects the table for the CourseModule model to be named course_modules. Which should be the table name if you want to follow the conventions.

If you want to keep the table name as course_module you can defiine which table to use in the CourseModule model.

See the example below

class CourseModule extends Model
{
    protected $table = 'course_module';

	// Rest of the code in your model
1 like
gych's avatar

@webter2 You just need to change the table name in your migration schema to course_modules

  Schema::create('course_modules', function (Blueprint $table) {

Please or to participate in this conversation.