2
votes

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');
}
3

3 Answers

0
votes

You have two alternatives :

  • First one :

    $data = $request->all();
    $data['user_id'] = Auth::user()->id;
    Project::create($data);
    //....
    
  • Second one :

    Auth::user()->project()->create($request->all());
    
0
votes

As you defined the projects table, user_id is not nullable. So if you want to insert a project, you have to pass a valid user_id to the create() call.

0
votes

You can get the user then use that to create the project like so:

$user = auth()->user();
$user->project()->create([
     $request->all()
]);

The advantage of this is that you don't have to put the 'user_id' directly as $fillable. Of course you would want to add those (other) fields to fillable in the model (since you are using create() method)

One thing observed is the pluralization of your related model, I think you can avoid confusion by using projects rather than project since its one user to many projects.