路由模型绑定不起作用 [英] Route Model Binding not working

查看:41
本文介绍了路由模型绑定不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将路由模型绑定用于简单的 CRUD,但更新和删除功能不起作用.我正在使用 laravel 5.5

I'm trying to use Route Model Binding for Simple CRUD but Update And Delete Function Not Working. and I'm Using laravel 5.5

Route::resource('admin/file','AdminController');

我的编辑和删除按钮视图

My View For Edit and Delete Buttons

<a href="{{ route('file.edit', ['id'=>$file->id]) }}">

<form action="{{ route('file.destroy', ['id'=>$file->id]) }}" method="post">
   {{method_field('DELETE')}}
   {{csrf_field()}}
   <button type="submit" class="delete">delete</button>
</form>

我的资源控制器:

namespace App\Http\Controllers;

use App\Files;
use Illuminate\Http\Request;

商店工作正常

  public function store(Request $request)
{
    $this->validate($request,[
        'title'=>'required',
        'body'=>'required',
        'price'=>'required',
        'linkFile'=>'required',
    ]);

     Files::create($request->all());
    return redirect(route('file.index'));
}

但编辑和删除不起作用

public function edit(Files $files)
{
   return view('admin.edit',compact('files'))->with('title','Edit File');
}

public function destroy(Files $files)
{
    $files->delete();
    return redirect(route('file.index'));
}

我的模型:

protected $table='files';

protected $fillable=[
    'title','body','price','linkFile'
];

当我删除按钮时什么也没有发生并编辑为相同

When I Delete Button Nothing Happens and Edit as Same

如果我在第一列添加 dd($files) 进行编辑和删除功能,那么响应将是 [] 并且句柄没有错误

If I Add dd($files) at First Column for Edit and Delete Function Then Response Will be [] and There's No Error for handle

这里是我的路线列表

有人可以帮忙吗?

推荐答案

终于,2 天后我找到了我的答案,我想在这里为每个可能遇到同样问题的人提供我的答案.

Finally, after 2 days I found my answer and I would like to provide my answer here for everyone who maybe has the same problem.

为了使路由绑定起作用,您应该让类型提示的变量名称与路由段名称匹配,如文档要求:

For route binding to work you should have type-hinted variable names match a route segment name, as the doc required :

例如我的编辑方法

这里是我要编辑的路由 URI

Here my route URI for edit

admin/file/{file}/edit

如您所见,有 {file} 参数或您调用的任何内容现在只需要在函数参数中准确地写$file

As you can see there is {file} parameter or anything you call now just need write exactly $file in function parameter

public function edit(Files $file)
{
   return view('admin.edit',compact('file'));
}

这篇关于路由模型绑定不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆