【发布时间】:2017-10-25 14:21:16
【问题描述】:
我的博客文章的“编辑”视图是通过如下所示的索引视图访问的:
@extends('layouts.app')
@section('stylesheet')
<link rel="stylesheet" href="{{ asset('css/backend.css') }}">
@endsection
@section('content')
<h1 class="backend_title">Viewing All Posts</h1>
<hr class="divider">
@foreach( $posts as $post )
<div class="backend_index-listing">
<label class="backend_index-listing_title">{{ $post->title }}</label>
<div class="backend_route-group">
<a class="backend_route" href="{{ route('posts.edit', $post) }}">Edit</a>
<form method="POST" action="{{ route('posts.destroy', $post) }}">
{{ csrf_field() }}
<input type="submit" value="Delete" class="backend_route">
<input type="hidden" name="_token" value="{{ Session::token() }}">
{{ method_field('DELETE') }}
</form>
</div>
</div>
@endforeach
@endsection
编辑视图如下:
@extends('layouts.app')
@section('stylesheet')
<link rel="stylesheet" href="{{ asset('css/backend.css') }}">
@endsection
@section('content')
<h1 class="backend_title">Edit Post</h1>
<hr class="divider">
<form class="backend_form" method="POST" action="{{ route('posts.update', $posts) }}">
{{ csrf_field() }}
<div class="backend_form-group">
<label for="title" class="backend_label">Title</label>
<input id="title" name="title" class="backend_input" required value="{{ $posts->title }}">
</div>
<div class="backend_form-group">
<label for="slug" class="backend_label">Slug</label>
<input id="slug" name="slug" class="backend_input" required value="{{ $posts->slug }}">
</div>
<div class="backend_form-group">
<label for="body" class="backend_label">{{ $posts->body }}</label>
<textarea id="body" name="body" class="backend_textarea" rows="40" required>{{ $posts->body }}</textarea>
</div>
<input class="backend_submit" type="submit" value="Update">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
@endsection
这是PostsController中的编辑功能。
public function edit(Posts $posts)
{
return view('posts.edit')->withPosts($posts);
}
还有更新功能。
public function update(Request $request, Posts $posts)
{
$this->validate($request, array(
'title' => 'required|255',
'slug' => 'required|255',
'body' => 'required'
));
$posts->title = $request->title;
$posts->slug = $request->slug;
$posts->body = $request->body;
$posts->save();
return redirect('posts');
}
我有一个通过我的创建表单创建的测试帖子,因此创建和存储工作正常。它在我想要的信息的索引上显示得很好。但是当我点击编辑按钮时,它会将我带到一个空的编辑视图,如果我填写字段并点击更新按钮,我会得到标题中的“MethodNotAllowed”异常。
【问题讨论】:
-
你能不能也显示你的更新路线
-
没有明确的更新路线。我使用了 Laravel 的资源路由语法并声明了
Route::resource('posts', PostsController)。它显示在php artisan route:list中,URI 为posts/{post} -
因为您的导航编辑 url 使用锚标签。锚标签不是 post 方法,所以它抛出方法错误。而不是锚点尝试使用 post 方法提交表单或保持锚点并更改您的路线以获取方法。 @user968270
-
在资源路径编辑方法中已经使用控制器中的 get 方法创建了 id 参数,但是您正在将数组传递给其中
-
edit 方法不是使用 ID 参数创建的,尽管我知道它应该是过去的,并且已经在我构建的两个 Laravel 应用程序中。正如您在上面看到的,资源控制器中的“编辑”功能是使用参数
(Posts $posts)构建的,这就是 artisan 命令的方式。