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!
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');