php - Laravel 路由模型绑定:销毁方法没有获取必要的信息
问题描述
这是我的 ProducerType 模型控制器:
namespace App\Http\Controllers;
use App\ProducerType;
use App\Http\Requests\ValidateProducerTypes;
use Illuminate\Http\Request;
class ProducerTypeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
...
public function destroy(ProducerType $producerType)
{
$producerType->delete();
return redirect('/producers');
}
}
这是我的模型:
namespace App;
use Illuminate\Database\Eloquent\Model;
class ProducerType extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'nome'
];
}
看法:
<form action="/producers-type/{{ $type->id }}" method="POST">
@csrf
@method('DELETE')
<button type="submit" class="btn-icon">
<img src="{{ asset('images/times-circle-regular.svg') }}" alt="">
</button>
</form>
路线:
Route::resource('producers-type', 'ProducerTypeController', [
'only' => ['store', 'update', 'destroy']
])->middleware('permission:create users');
我的问题是:$producerType
变量没有抓住必要的属性。
解决方案
虽然上面的答案给出了问题的解决方案,但我最终在我的代码中发现了问题!
来自Route Model Binding的 Laravel 文档:
由于 $user 变量的类型提示为 App\User Eloquent 模型,并且变量名称与 {user} URI 段匹配,Laravel 将自动注入 ID 与请求 URI 中相应值匹配的模型实例。如果在数据库中没有找到匹配的模型实例,将自动生成 404 HTTP 响应。
这是我的问题:我正在使用$producerType
变量,Laravel 期待$producers_type
因为我的路线producers-type/{producers_type}
。