laravel 资源控制器中的呼叫销毁方法

ojsjcaue  于 2023-01-14  发布在  其他
关注(0)|答案(2)|浏览(136)

当我在laravel.delete.blade.php中使用资源控制器时,我不明白如何调用destroy方法

@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

资源控制器:

<?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::resource('posts', 'PostController');

当GET请求被传递时,它正在调用show方法。请指导我如何调用destroy方法。正如文档中提到的,我正在使用表单方法欺骗传递@method('DELETE'),因为html只识别GET和POST方法。

tjjdgumg

tjjdgumg1#

你可以使用下面的代码。我希望它能工作。

<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!');
}
cvxl0en2

cvxl0en22#

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 class="ft-trash"></i>delete', array('type' => 'submit','class' => 'btn btn-defult','title' => 'Delete Post','onclick'=>'return confirm("Confirm delete?")')) !!}

{!! Form::close() !!}

相关问题