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

Laravel5.5中如何修改findOrFail方法的主键名称?

How to Change Default Primary Key from id to a_id in Laravel Model

Hey there! Let's get this sorted out for you. The issue has two key parts: telling your Laravel model to use a_id as the primary key, and fixing the incorrect findOrFail call in your controller.

Step 1: Update Your Article Model

Laravel assumes the primary key is named id by default, so we need to explicitly override this in your Article model.

Open your Article model file (usually located at app/Models/Article.php) and add the $primaryKey property:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    // Set your custom primary key column name
    protected $primaryKey = 'a_id';

    // Optional: Uncomment these lines ONLY if your `a_id` is not an auto-incrementing integer
    // public $incrementing = false;
    // protected $keyType = 'string'; // Use this if your primary key is a string type
}

Step 2: Fix the findOrFail Call in Your Controller

Your original findOrFail usage was wrong—this method automatically uses the model's defined primary key, so you don't need to pass the column name as a parameter. Just pass the primary key value directly.

Update your controller method to this:

public function edit($a_id) { 
    $articleData = Article::findOrFail($a_id); 
    return view('Admin.articleEdit')->with('articleData',$articleData); 
}

Why This Works

By setting $primaryKey = 'a_id' in the model, all Laravel's built-in methods that rely on the primary key (like find, findOrFail, delete, etc.) will now use a_id instead of the default id. The findOrFail method will automatically run a query like SELECT * FROM articles WHERE a_id = ? under the hood, using the value you pass to it.

内容的提问来源于stack exchange,提问作者seven

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:37:46