Laravel执行migrate报错BadMethodCallException:Blueprint::after不存在如何解决
报错原因
- 核心问题是
after方法使用不符合Laravel语法规则:Illuminate\Database\Schema\Blueprint类不存在接收闭包参数的after()方法。after是单个字段的修饰符,只能跟在具体字段定义的后面,用于指定新增字段在表中的排列位置,不能用来批量包裹多个字段操作,因此触发了方法不存在的异常。
修复方案
- 修正迁移文件代码,调整写法如下:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class UpdateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table){ // 重命名原有name字段为fname $table->renameColumn('name', 'fname'); // 每个新增字段单独通过after指定排列位置 $table->string('lname')->after('fname'); $table->boolean('sex')->after('lname'); $table->date('b_day')->default('2021-01-01')->after('sex'); $table->string('image')->after('b_day'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { // 回滚时先删除新增字段,再把fname改回name $table->dropColumn(['lname', 'sex', 'b_day', 'image']); $table->renameColumn('fname', 'name'); }); } }
- 若你使用的Laravel版本低于9,需要先安装重命名字段依赖的扩展包,在项目根目录执行以下命令:
composer require doctrine/dbal - 重新执行迁移命令即可:
php artisan migrate
内容的提问来源于stack exchange,提问作者Rajib Bin Alam
相关产品推荐
相关产品推荐

