Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.7K
Views
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null in laravel

I create a todo app in laravel with vue. I have two tables: users and todos; every user has many todos like this: User.php model:

class User extends Authenticatable {
    protected $fillable = [
        'name', 'email', 'password',
    ];
    public function todos()
    {
        return $this->hasMany(
            Todos::class,
            'user_id',
            'user_id'
        );
    }
}

Todos.php model:

class Todos extends Model
{
    //
    protected $fillable = ['title', 'completed', 'user_id'];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

then I defined this route:

Route::post('/v1/todo', 'todosController@addTodo');

this is my addTodo from todosController:

 public function addTodo(Request $request)
    {
        $uid = Auth::user()->id;
        //dd($uid);

        $todoCreated = new Todos([
            'title' => $request->input('title'),
            'completed' => 0
        ]);
        $user = User::find($uid);
        //dd($user);

        //dd($todoCreated);
        dd($user->todos()->create([
            'title' => $request->input('title'),
            'completed' => 0,
        ]));
}

when I send form data it shows me this error:Illuminate\Database\QueryException SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into todos (title, completed, user_id, updated_at, created_at) values (darya, 0, ?, 2020-07-06 12:17:45, 2020-07-06 12:17:45)). I am new in laravel and I appreciate any help!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You've passed wrong param in relationship.

public function todos()
{
    return $this->hasMany(
        Todos::class,'user_id','id'
    );
}


return $this->hasMany(Todos::class, 'foreign_key', 'local_key');
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!