Ошибка перенаправления в контроллере

I cant seem to fix my issue when i delete a task it redirects me to dashboard i can see in controller it is currently redirecting to /dashboard page however when i try to fix this it just errors out :/ i want it to acheive the same result the create redirection does.

public function createTaskPage(Request $request, $slug) {

    $project = Project::where('slug', $slug)->firstOrFail();

    // Validate it has a body.
    $validate = validator(
            $request->toArray(), [
        'task' => 'required',
    ]);

    if ($validate->fails()) {
        return response()->json([], 400);
    }
    $tasks = new Task;
    $tasks->project_id = $project->id;
    $tasks->body = $request->task;
    $tasksCreate = Auth::user()->tasks()->save($tasks);
    //return response()->json([], 201);
    return redirect()->to('/project/' . $project->slug);
}

public function doDeleteTask($id) {
    try {
        $tasks = Task::where('user_id', Auth::user()->id)->findOrFail($id);
    } catch (IlluminateDatabaseEloquentModelNotFoundException $ex) {
        return response()->json([], 404);
    }
    $tasks->delete();
    //return response()->json([], 204);
    return redirect()->to('/dashboard');
}

Это форма, где кнопка удаления

<div class="col-md-3">
<div class="panel panel-default shadow">
    <div class="panel-body">
        <div class="row text-center">
            <h4><strong>{{ str_limit(strip_tags($project->name), 20) }}</strong></h4>
            <h5>{{ $project->created_at }}</h5>
        </div>
        <div class="row text-center" style="margin:5px;">
            {{ ($project->description) }}
        </div>
        <div class="row text-center">
            <form action="{{ url('/project/'.$project->id) }}" method="POST">
                {{ csrf_field() }}
                {{ method_field('DELETE') }}
                <button type="submit" class="btn btn-link btn-sm" onclick="return ConfirmDelete(this)" style="margin:5px;"><i class="fa fa-ban fa-3x" aria-hidden="true"></i></button>
                <a href="{{ url('/project/' . $project->slug) }}" class="btn btn-link btn-sm"><i class="fa fa-arrow-circle-o-right fa-3x" aria-hidden="true"></i></a>
            </form>              
        </div>
    </div>
</div>

Это мой удалить маршрут и создать маршрут

Route::delete('/task/{id}', 'TaskController@doDeleteTask'); // Delete a task
Route::post('/project/{slug}/task', 'TaskController@createTaskPage')->name('task');

1 ответ

  1. Если у вас есть связь проекта, определенная в задачах, вы можете сделать это:

    public function doDeleteTask($id) {
        try {
            $tasks = Task::where('user_id', Auth::user()->id)->findOrFail($id);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $ex) {
            return response()->json([], 404);
        }
       $project = $tasks->project;
       $tasks->delete();
    
       return redirect()->to('/project/' . $project->slug);
    }