I'm relatively new to Laravel and I am trying to make a forum using eloquent.
I used the make:auth command to make a users migration and created a threads migration using mysql workbench and a plugin to convert the ERD to a migration:
Schema::create($this->set_schema_table, function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('title', 45)->nullable();
$table->text('description')->nullable();
$table->timestamp('created_at')->nullable()->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->nullable()->default(DB::raw('CURRENT_TIMESTAMP'));
$table->unsignedInteger('created_by');
$table->index(["created_by"], 'fk_threads_users1_idx');
$table->foreign('created_by', 'fk_threads_users1_idx')
->references('id')->on('users')
->onDelete('no action')
->onUpdate('no action');
});
After that I created a model for threads and extended the user model to specify the relationship between the two:
class Thread extends Model
{
// No fields are protected in the database
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class, 'created_by');
}
}
and
class User extends Authenticatable
{
public function threads(){
return $this->hasMany(Thread::class);
}
public function publish(Thread $thread){
$this->threads()->save($thread);
}
}
At first this worked fine, but somehow after running php artisan cache:clear (or maybe something else may have caused the code to stop working, I am not sure) the store method in the thread controller gave me an error:
Column not found: 1054 Unknown column 'user_id' in 'field list'
(SQL: insert into `threads` (`title`, `content`, `user_id`, `updated_at`, `created_at`)
values (Thread 4, content, 17, 2017-11-23 11:16:24, 2017-11-23 11:16:24))`
As you can see it's trying to find the field "user_id" while I specified the foreign key should be "created_by" in the user method in the Thread class.
I'm pretty sure everything worked at fine at first. Does anyone know how to fix this?