正在删除模型及其相关模型 returns 状态代码 404,但已删除

Deleting model and its related model returns status code 404, but its deleted

我有一个名为 DeletePost.php 的作业执行删除操作,post 模型有两个相关模型。执行dispatchSync到运行作业后,所有模型及相关模型都被正确删除,但是returns404.

我可以从 debugbar 得到的唯一例外是。并且只提出了一个请求。

web.php

Route::delete('/user/profile/post/delete/{post}', [PostController::class, 'destroy'])
  ->where('postId', '[0-9]+')
  ->name('account.post.destroy');

App/http/controller/PostController.php

public function destroy(Post $post)
    {
        $this->authorize(PostPolicy::DELETE, $post);

        $this->dispatchSync(new DeletePost($post));

        return redirect()->route('dashboard')->with('success', ['Successful !', 'Post deleted successfully']);
    }

App/Job/DeletePost

<?php

namespace App\Jobs;

use App\Models\Post;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class DeletePost implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(private readonly Post $post)
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle() :void
    {
        $this->post->delete();
    }
}

Note that I have overwritten the delete method in my post model.

App/model/Post.php

public function delete(){
    $this->removePostPhotos();

    parent::delete();
}

public function removePostPhotos()
{
    $this->postPhotosRelation()->delete();

    $this->unsetRelation('postPhotosRelation');
}

Forntend

deletePost() {
            Inertia.delete(route("account.post.destroy", [this.post.id]), {
                method: "DELETE",
                preserveScroll: true,
            });
        },

@apokryfos 在你向服务器提交 delete 请求后指出了问题,服务器首先删除 post 然后响应,这就是为什么我得到 404

我想出了一个解决方案,您先响应,然后调度作业。

public function destroy(Post $post)
    {
        $this->authorize(PostPolicy::DELETE, $post);

        DeletePost::dispatchAfterResponse($post);

        return redirect()->back()->with('success', ['Successful !', 'Post deleted successfully']);
    }

use the dispatchAfterResponse method when you dispatch the job.