I have users and projects table. in project table user_id is foreign key. i create a project and when i try to save the project details its showing this ERROR:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (labtest.projects, CONSTRAINT projects_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON UPDATE CASCADE) (SQL: insert into Projects (name, description, date, updated_at, created_at) values (e, e, 2017-12-31, 2017-09-19 15:21:06, 2017-09-19 15:21:06))
how i can solve this?
users table migration:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
projects table migration
Schema::create('projects', function (Blueprint $table) {
$table->increments('id')->unique();
$table->string('name');
$table->text('description');
$table->date('date');
$table->timestamps('date');
});
Schema::table('projects',function(Blueprint $table)
{
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')
->onUpdate('cascade');
});
user model:
public function project()
{
return $this->hasMany('App\Project');
}
project model:
public function user() {
return $this->belongsTo('App\User','id','user_id');
}
controller:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'date' => 'required',
]);
Project::create($request->all());
return redirect()->route('projects.index')
->with('success','Project created successfully');
}