You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.2博客点赞功能报错:BadMethodCallException likes()未定义

解决Laravel 5.2中Builder::likes()未定义的错误

Hey there! Let's break down why you're seeing this BadMethodCallException and fix it step by step.

核心原因:缺少关联所需的外键字段

The most common culprit here is that your likes database table doesn't have a post_id field—Laravel's hasMany/belongsTo relationships rely on this field to link posts and likes. When this field is missing, Laravel can't properly resolve the likes() relationship method on your Post model, leading it to mistakenly try calling a non-existent likes() method on the query builder instead.

修复步骤

1. 添加post_id外键到likes表

First, we need to add the required foreign key column to your likes table:

  • Generate a migration to modify the likes table:
    php artisan make:migration add_post_id_to_likes_table --table=likes
    
  • Open the new migration file (located in database/migrations) and update the up() and down() methods:
    public function up()
    {
        Schema::table('likes', function (Blueprint $table) {
            // Add unsigned integer column (matches the type of posts.id)
            $table->integer('post_id')->unsigned();
            // Add foreign key constraint to enforce referential integrity
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
        });
    }
    
    public function down()
    {
        Schema::table('likes', function (Blueprint $table) {
            $table->dropForeign(['post_id']);
            $table->dropColumn('post_id');
        });
    }
    
  • Run the migration to apply the changes:
    php artisan migrate
    

2. 优化控制器代码(可选但推荐)

To avoid potential issues with null models, replace Post::find($id) with findOrFail($id)—this will automatically return a 404 error if the post doesn't exist, instead of letting the code try to call likes() on a null value:

public function getLikePost($id) {
    $post = Post::findOrFail($id);
    // You can also simplify the save call using create()
    $post->likes()->create([]);
    return redirect()->back();
}

3. (可选)更新Like模型的可填充字段

While not required for this specific case, adding post_id to the $fillable array in your Like model will let you use mass assignment later if needed:

class Like extends Model {
    protected $fillable = ['post_id'];

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

验证修复

After making these changes, try clicking the like button again. The relationship should now resolve correctly, and the like will be saved to the database with the correct post_id value.

内容的提问来源于stack exchange,提问作者D. Elliott

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:56:32