I am building a project in Laravel on trying to persist a record in the database for the model Content that I have set up like this:
class Content extends Model
{
/**
* The attributes that are guarded by mass assignable.
*
* @var array
*/
protected $guarded = [
'id'
];
public function contentType()
{
return $this->hasOne('App\ContentType');
}
}
In my controller I am first saving the record in the content_types table like this:
public function resolveType($type)
{
return ContentType::firstOrCreate(
['name' => $type,
'slug' => str_slug($type, '-')]
);
}
And then I am saving the content:
Content::create([
'ct_id' => $post->ID,
'cms_id' => '',
'title' => $post->post_title,
'slug' => str_slug($post->post_title, '-'),
'excerpt' => $post->post_excerpt,
'body' => $this->formatBodyImages($post->post_content),
'password' => $post->post_password,
'parent_id' => $post->post_parent,
]);
The ContentType model is set up like this:
class ContentType extends Model
{
/**
* The attributes that are guarded by mass assignable.
*
* @var array
*/
protected $guarded = [
'id'
];
public function contents()
{
return $this->hasMany('App\Content', 'ct_id');
}
}
So, when I try to persist new content record, I get the error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
middleton
.contents
, CONSTRAINTcontents_ct_id_foreign
FOREIGN KEY (ct_id
) REFERENCEScontent_types
(id
)) (SQL: insert intocontents
(cms_id
,title
,slug
,excerpt
,body
,password
,parent_id
,updated_at
,created_at
)