laravel8への移植で、$id以外の独自キーを使っているテーブルでCRUDを作る場合は、getRouteKeyName()でキーを指定する!
1. 必要なファイルを生成
| 1 | php artisan make:model OreOre --all | 
2. 移植先テーブル定義
| 1 2 3 4 5 6 7 | Schema::create('OreOres', function (Blueprint $table) {     $table->id()->comment('');     $table->string('OreOreCode')->unique()->comment('オレオレコード。これを外部キーに使われたりしている');     $table->string('OreOreName')->comment('オレオレ名');     $table->timestamps();     $table->softDeletes(); }); | 
3. Restfulなルーティング
| 1 | Route::Resource('OreOre', OreOreController::class); | 
4. 素直にidカラムがあれば、何も考えずにデフォルトのままでOK
| 1 2 3 4 5 | // http://localhost/laravel8/public/oreore/1 public function show(OreOre $oreore) {     return $oreore; } | 
5. OreOreCode=1のレコードを表示したい!
app/Models/Railroad.phpにgetRouteKeyName()を追加
これで、idの代わりにOreOreCodeが使える!
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // http://localhost/laravel8/public/oreore/1 class OreOre extends Model {     // id以外のカラムは自由にinsert/updateしてOK!     protected $guarded = ['id'];         // id以外をキーにしたい時は、カラム名を指定する     public function getRouteKeyName()     {         return 'OreOreCode';     }     use HasFactory; } |