Dércio Lichucha
Dércio Lichucha

Reputation: 63

Laravel 5.5 Method update doesn't exist

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

Answers (3)

Sithira
Sithira

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

YouneL
YouneL

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

Sohel0415
Sohel0415

Reputation: 9863

$posts = Post::find($post->id);

find() accepts only primary id

Upvotes: 1

Related Questions