Laravel5.5中如何修改findOrFail方法的主键名称?
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

