如何在laravel中使用预定义的销毁方法

Bra*_*iac 0 php routes laravel

我想知道删除由模型制成的对象的最佳实践方法?我见过几个类似的问题,但没有人触及整个主题,也没有人进一步触及我的具体细节。

我想创建一个删除按钮,删除 laravel 中的特定对象。我知道如何做到这一点,但恐怕我让事情变得过于复杂了。

假设我有一个名为 Post 的模型

我还有控制器 PostController。当我制作这个控制器时,我为其提供了资源。因此,我准备了几种方法,例如。破坏

 /**
 * Remove the specified resource from storage.
 *
 * @param  \App\Post  $post
 * @return \Illuminate\Http\Response
 */
public function destroy(Post $post)
{
    //
}
Run Code Online (Sandbox Code Playgroud)

我有点困惑,好像为什么它给我类型提示Post以及 $post 参数?对我来说,如果将 $id 作为参数就有意义了。

但一次又一次,我不是泰泰。所以每当有些事情对我来说没有意义时,我就认为我错过了一些事情。那么,冒着过于宽泛的风险,如何制作使用预定义销毁方法的删除按钮?我正在寻找这三个步骤的答案:

  1. HTML(如何制作表单/按钮)
  2. web.php(路线)
  3. PostController(我如何执行销毁?我知道如何使用 id 来执行此操作,但将整个对象作为参数?首先是如何发送的?)

Tha*_*han 6

他们这样做只是为了更加明智。
喜欢跟上Object Oriented

别担心。即使它有destroy(Post $post),您也不必Post为该destroy()函数提供对象。您只需id通过 传递帖子的request。其余的由 Laravel 处理。

Laravel 在 post 表中查找具有您在请求中传递的 id 的帖子,然后获取该 post 对象并将其提供给函数destroy()

你只需要调用delete()它即可。

public function destroy(Post $post)
{
    // laravel has found the post for you.
    $post->delete();
}
Run Code Online (Sandbox Code Playgroud)

让我们看看您的方法。
你可以将其更改为destroy($id)

public function destroy($id)
{
    // you have to find the particular post from database to delete.
    Post::where('id', $id)->delete();
}
Run Code Online (Sandbox Code Playgroud)

你看,事情更复杂了。

所以回答你的3个问题。

形式

<form method="post" action="{{ route('post.destroy'), 1 }}">
    <!-- here the '1' is the id of the post which you want to delete -->

    {{ csrf_field() }}
    {{ method_field('DELETE') }}

    <button type="submit">Delete</button>
</form>
Run Code Online (Sandbox Code Playgroud)

路线

Route::resource('post', 'PostController');
Run Code Online (Sandbox Code Playgroud)

控制器

public function destroy(Post $post)
{
    $post->delete();
}
Run Code Online (Sandbox Code Playgroud)