Laravel - delete method does not exist
I get an error:
BadMethodCallException at line Macroable.php 74: The delete method does not exist.
route:
Route::resource('posts', 'PostController');
my controller:
public function destroy($id)
{
$user_id = Auth::user();
$post= Post::where('id', $id)->where('user_id',$user_id)->get();
$post->delete();
return view('/home', [
'posts' => $post
]);
}
Look:
<form action="{{ route('posts.destroy', '$post->id') }}" method="post">
<input type="hidden" name="_method" value="DELETE" />
{{ csrf_field() }}
{{ method_field('DELETE') }}
<input type="submit" class="btn btn-danger" value="delete" />
</form>
I tried to change method="post"
so that delete
: the error is gone, but nothing is removed ..
source to share
Remove get () and it will work
$post= Post::where('id', $id)->where('user_id',$user_id);
$post->delete();
If you want to delete first document you can use :
$post= Post::where('id', $id)->where('user_id',$user_id)->first();
$post->delete();
However, you always need to check if $ post is found as a request document or is null, so addd:
if($post){
$post->delete();
}
source to share
controller:
public function destroy($id)
{
$post = Post::find($id);
$post->delete();
//redirect to
return redirect()->back();
}
View:
{!! Form::open(['method' => 'DELETE','route' => ['posts.destroy', $post->id],'style'=>'display:inline']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
Try it.
hope you created the controller with
- resource
flag.
source to share
Since the post id is the primary key of the table, posts
you can directly remove it from the table, there is
no need foruser_id
To get user_id from Auth facade you have to use,
$user_id = Auth::id();
Only passing the ID should work,
Post::find($id)->delete()
However, if you know the primary key of the model, you can delete the model without retrieving it by calling the destroy
. In addition to a single primary key, the method destroy
will accept multiple primary keys, an array of primary keys, or a collection of primary keys as an argument :
Post::destroy($id)
source to share
In your controller
Before changing the code
public function destroy($id)
{
$user_id = Auth::user();
$post= Post::where('id', $id)->where('user_id',$user_id)->get();
$post->delete();
return view('/home', [
'posts' => $post
]);
}
After changing the code
public function destroy($id)
{
$user_id = Auth::user();
$post= Post::where(['id'=>$id,'user_id'=>$user_id])->get();
Post::where(['id'=>$id,'user_id'=>$user_id])->delete();
return view('/home', [
'posts' => $post
]);
}
source to share
Just add this on top, I was wrong like you and now solved, sorry for bad english.
{!! Form::model($post, ['route' => ['posts.destroy', $post->id], 'method' => 'DELETE']) !!}
and
{!! Form::close() !!}
down below
for controller
$post = Post::find($id);
$post->delete();
Session::flash('success', 'Menu was successfully deleted!');
return redirect()->route('posts.index');
source to share