Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cjholowatyj's avatar

Laravel Nova Creating DB Queries to Non-Existent Column

Running Laravel 10 / Laravel Nova 4.24.4 ...

I'm having trouble connecting two related models to each other (Blogs and Posts), specifically getting Nova to generate the correct MySQL query when creating a Post record. Nova seems to be adding a non-existent blogs_id field to the insert query on the posts table...

The relationship should be: Blogs > hasMany > Posts (i.e. Posts > belongsTo > Blogs)

# \App\Nova\Blog fields array includes:
[... HasMany::make('Posts'), ...]

# \App\Nova\Post fields array includes:
[... BelongsTo::make('Blog','blog',\App\Nova\Blog::class), ...]

# \App\Models\Blog includes:
class Blog extends Model{
   protected $table='blogs';
   protected $with=['posts'];
   public function posts():HasMany{
      return $this->hasMany(\App\Models\Post::class);
   }
}

# \App\Nova\Post includes:
class Post extends Model{
   protected $table='posts';
   public function blog():BelongsTo{
      return $this->belongsTo(Blog::class);
   }
}

The SQL query that is generated by Nova when trying to save a new post to the database is something like (backticks omitted for formatting)...

insert into posts ( ... blogs_id, ... blog_id, ... )

The blog_id field is accurately represented, but there's also this additional blogs_id field which is being generated that I cannot seem to figure out the source of (and it breaks the query because blogs_id doesn't exist)

0 likes
3 replies
LaryAI's avatar
Level 58

The issue seems to be with the naming convention used for the relationship between the Blog and Post models. By default, Laravel assumes that the foreign key for a hasMany relationship is the singular form of the related model's name followed by _id. In this case, Laravel is incorrectly assuming that the foreign key for the hasMany relationship in the Blog model is blogs_id.

To fix this issue, you can explicitly specify the foreign key in the hasMany relationship in the Blog model. Update the posts method in the Blog model as follows:

public function posts(): HasMany
{
    return $this->hasMany(\App\Models\Post::class, 'blog_id');
}

By specifying 'blog_id' as the second argument to the hasMany method, you are telling Laravel to use blog_id as the foreign key instead of the default blogs_id.

After making this change, Nova should generate the correct MySQL query without the non-existent blogs_id field.

1 like
cjholowatyj's avatar

@LaryAI Finally an AI response that led me to a solution! I declared the foreignKey and ownerKey explicitly when defining the relationship on both models, and finally things work.

krisi_gjika's avatar

@cjholowatyj what happens if you comment out the blog field on the post resource? what is the resulting query than? is blog_id or blogs_id or both removed?

Please or to participate in this conversation.