0
votes

I have users table with id on it.
My project model has $fillable fields:

  protected $fillable = [
    'title',
    'description',
    'visibility_level',
    'creator_id'
  ];

relationship:

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

In Users model relationship:

  public function projects()
  {
    return $this->hasMany('App\Project');
  }

Now creator_id is refering to user_id. I have set up my project model table with:

  $table->foreign('creator_id')->references('id')->on('users')
    ->onUpdate('cascade')->onDelete('cascade');

But then I try to store data, it still tried to add user_id:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'field list' 

My store() method:

public function store(ProjectRequest $request)
{

$project = new Project($request->all());

Auth::user()->projects()->save($project);

flash()->success('Project have been created');

return redirect('news/');
}

Am I searching In wrong place or what? I dont understand why its "user_id" where is this "user_id" generated name comes from?

1

1 Answers

2
votes

The user_id key comes from the name of your class (User). All laravel does is snake case it and append _id to it. To fix your issue, use the second, optional, parameter for hasMany on your User class:

public function projects()
{
    return $this->hasMany('App\Project', 'creator_id');
}

This should solve your problems now but, to use the relationship the other direction, you'll also need to make some changes on your Project model. You have two choices:

  1. Rename your relationship method:

    public function creator()
    {
        return $this->belongsTo('App\User');
    }
    
  2. Override the key by passing it as second parameter to belongsTo:

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

Given what you are trying to achieve, I'd recommend you go with the first option.