I have a job called DeletePost.php which performs the delete action, the post model has two related models. After performing dispatchSync to run the job, all the model and related model were deleted correctly, but it returns 404.
The only exception I can get from debugbar is that. and only one request being made.
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
deletemethod in mypostmodel.
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,
});
},
CodePudding user response:
@apokryfos has pointed out the problem after you submit a delete request to the server, the server delete the post first then response that's why I am getting 404
I have figured out a solution where you respond first and then dispatch the jobs.
public function destroy(Post $post)
{
$this->authorize(PostPolicy::DELETE, $post);
DeletePost::dispatchAfterResponse($post);
return redirect()->back()->with('success', ['Successful !', 'Post deleted successfully']);
}
use the
dispatchAfterResponsemethod when you dispatch the job.



