Search code examples
laraveleloquentmany-to-many

Laravel: cannot insert into many to many relationship


i hope you're having a good day.

so i have this ManyToMany relationship where a user can apply to multiple jobs, and a job can have multiple applicants (users).

here is the table schema

        Schema::create('applicant_job', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('job_id');
            $table->unsignedBigInteger('applicant_id');

            $table->unique(['job_id', 'applicant_id']);


            $table->foreign('job_id')
                ->references('id')
                ->on('jobs')
                ->onDelete('cascade');


            $table->foreign('applicant_id')
                ->references('id')
                ->on('default_users')
                ->onDelete('cascade');

        });

and here is the model code.

DefaultUser.php

class DefaultUser extends Model
{
  
    public function user()
    {
        return $this->morphOne(User::class, 'userable');
    }

    public function applications()
    {
        return $this->belongsToMany(Job::class, 'applicant_job', 'job_id', 'applicant_id');
    }
}

and Job.php

class Job extends Model
{
    public function owner()
    {
        return $this->belongsTo(BusinessUser::class, 'business_user_id');
    }

    public function applicants()
    {
        return $this->belongsToMany(DefaultUser::class, 'applicant_job', 'applicant_id', 'job_id');
    }
}

everything seems ok and find, however when i try to save ( a user applying to a job), i get the following error enter image description here

i'm doing so inside ApplyToJobController.php


class ApplyToJobController extends Controller
{
    public function store(Job $job, Request $request) {
        $default_user = auth()->user()->userable;

        $job->applicants()->attach($default_user->id);

        return redirect("/en");
    }
}

and, Thank you very much for your answers.

EDIT

i have changed the column names to this

Schema::create('applicant_job', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('job_id');
            $table->unsignedBigInteger('default_user_id');

            $table->unique(['job_id', 'default_user_id']);


            $table->foreign('job_id')
                ->references('id')
                ->on('jobs')
                ->onDelete('cascade');


            $table->foreign('default_user_id')
                ->references('id')
                ->on('default_users')
                ->onDelete('cascade');

        });

it made it work, im curios any idea why?


Solution

  • Try to switch the order of the foreign keys in the applicants relation declared in the Job model like the example below :

    public function applicants()
    {
        return $this->belongsToMany(DefaultUser::class, 'applicant_job', 'job_id', 'applicant_id');
    }