I am unable to understand how to call destroy method when I use resource controller in laravel. delete.blade.php
@extends('main') @section('content') <form method="POST" action="{{route('posts.destroy', '$post->id') }}" > @method('DELETE') @csrf <select name="id"> <option value="1">vddv</option> <option value="2">miss</option> <option value="3">miss</option> <option value="4">joy</option> </select> <br><br> <button type="submit"> Delete blog</button> </form> @endsection resource controller :
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use App\posts; use Sessions; class PostController extends Controller { public function create() { return view('posts.create'); } public function store(Request $request) { $post = new posts; $post->title = $request->input('title'); $post->body = $request->input('body'); $post->save(); return redirect('posts/read'); } public function show($data) { echo "show"; } public function edit($id) { return view('posts.edit'); } public function update(Request $req, $id) { echo posts::where('title' , $req->title) ->update(['body'=>$req->body]); return redirect('/'); } public function destroy($id) { $post = posts::find($id); $post->delete(); return redirect('/'); } } route:
Route::resource('posts', 'PostController'); It is calling show method as GET request is passed. please guide me how to call destroy method. As mentioned in documentation I am passing @method('DELETE') using form method spoofing as html only recognise GET and POST method.
32 Answers
You can use below code. I hope it will work.
<form method="POST" action="{{ url('/posts' . '/' .$post->id) }}"> {{ method_field('DELETE') }} {{ csrf_field() }} <select name="id"> <option value="1">vddv</option> <option value="2">miss</option> <option value="3">miss</option> <option value="4">joy</option> </select> <button type="submit" title="Delete Post">Delete</button> </form> // In Controller public function destroy($id) { Post::destroy($id); return redirect('posts')->with('flash_message', 'Post deleted!'); } Hello, Brother please try this i hope it will work. {!! Form::open(['method'=>'DELETE', 'url' =>route('posts.destroy', $post->id),'style' => 'display:inline']) !!} {!! Form::button('<i></i>delete', array('type' => 'submit','class' => 'btn btn-defult','title' => 'Delete Post','onclick'=>'return confirm("Confirm delete?")')) !!} {!! Form::close() !!}