Reputation: 63
I'm trying to create a blog but I keep getting this error.
BadMethodCallException Method update does not exist.
I'm trying to edit posts and update the database.
public function update(Request $request, Post $post)
{
$posts = Post::Find($post);
$posts->update($request->all());
}
Upvotes: 0
Views: 4743
Reputation: 1016
you are already accepting the Post object via the method
rather doing something like this
public function update(Request $request, Post $post)
{
$posts = Post::Find($post);
$posts->update($request->all());
}
do it like this
public function update(Request $request, Post $post)
{
// you already have the Post object injected from the framework for you.
// you can use the instance freely.
$post->update($request->all());
}
of cause, it might be a good thing to check if the $post object is null or not but laravel will throw ModelNotFoundException if you don't have any matches in the database.
This is something called Route Model Binding which laravel 5.5 does for you if you keep the settings as default, as in using the primary key 'id'. you can read more about this on this https://laravel.com/docs/5.5/routing#route-model-binding
Upvotes: 5
Reputation: 8369
Do directly:
public function update(Request $request, Post $post) {
$post->update($request->all());
}
$post
is already an instance of Post
model if the route was declared as:
Route::get('posts/update/{post}', 'PsotsController@update');
Doc Reference: route model binding
Upvotes: 4