To update the post we need to work two routes and two methond in the PostController
posts/{post}/edit //GET
posts/{post} // PUT
We need to update the PostController and create a view for the edit form
<form method="POST" action="{{ route('posts.update',$post->id) }}">
@csrf
@method('PUT')
This view is likely to be similar to the create post view but you will need to
- update the form action to call the new route
- add the existing values into the form
resources/views/posts/edit.blade.php
<form method="POST" action="{{ route('posts.update') }}">
@csrf
@method('PUT')
/**
* Update the specified resource in storage.
*/
public function update(Request $request, Post $post)
{
$request->validate([
'title' => 'required',
'body' => 'required',
]);
Post::where('id', $post->id)->update(
[
'title' => $request->title,
'body' => $request->body,
'user_id' => 1 //or whatever user you want associated with the update
]
);
return redirect()->route('posts.index')->with('success', 'Post updated successfully.');
}
Common error: Model::update() should not be called statically
- Log in to post comments