laravel postをeditしよう

postController

public function edit(Post $post){
		return view('posts.edit')->with('post', $post);
    }

updateはget, postではなくpatch

@section('container')
<h1>
	<a href="{{ url('/') }}" class="header-menu">Back</a>
	Edit Post</h1>
<form method="post" action="{{ url('/posts', $post->id) }}">
	{{ csrf_field() }}
	{{ method_field('patch') }}
	<p>
		<input type="text" name="title" placeholder="enter title" value="{{ old('title', $post->title) }}">
		@if ($errors->has('title'))
		<span class="error">{{ $errors->first('title')}}</span>
		@endif
	</p>
	<p>
		<textarea name="body" placeholder="enter body">{{ old('body', $post->body)}}</textarea>
		@if ($errors->has('body'))
		<span class="error">{{ $errors->first('body')}}</span>
		@endif
	</p>
	<p>
		<input type="submit" value="Update">
	</p>
</form>
@endsection

なるほど、慣れるまで少し時間がかかるかも。

Routingはpatchにする。

Route::get('/', 'PostsController@index');
// Route::get('/posts/{id}', 'PostsController@show');
Route::get('/posts/{post}', 'PostsController@show')->where('post','[0-9]');
Route::get('/posts/create', 'PostsController@create');
Route::post('/posts', 'PostsController@store');
Route::get('/posts/{post}/edit', 'PostsController@edit');
Route::patch('/posts/{post}', 'PostsController@update');

PostsController.php
functionのupdateを追加

public function update(Request $request, Post $post){
    	$this->validate($request, [
    		'title' => 'required|min:3',
    		'body' => 'required',
    	]);
    	$post->title = $request->title;
    	$post->body = $request->body;
    	$post->save();
    	return redirect('/');
    }