Laravel 5.2-从数据库删除

时间:2018-10-29 05:33:09

标签: php laravel laravel-5

我正在使用Laravel Framework version 5.2.45

我创建了一个简单的视图来输出待办事项:

@foreach($todos as $todo)
    {{ $todo->todo }} <button href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</button>

    <hr>
@endforeach

在我的路线内,我创建了以下路线以删除todo

Route::get('/todo/delete/{id}', [
    'uses' => 'TodosController@delete',
    'as' => 'todo.delete'
]);

在我的TodosController中,我创建了以下delete方法:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Todo;

class TodosController extends Controller
{

    public function delete($id) {
        $todo = Todo::find($id);

        $todo->delete();

        return redirect()->back();
    }
// ...

当我按下前端的按钮时,什么也没发生。我没有任何错误...

有人建议我的实现有什么问题吗?

感谢您的答复!

4 个答案:

答案 0 :(得分:2)

尝试以下代码,您已使用按钮代替了标签

@foreach($todos as $todo)
            {{ $todo->todo }} <a href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</a>

            <hr>
        @endforeach

答案 1 :(得分:2)

您正在使用未标记的按钮

打开您的代码

@foreach($todos as $todo)
   {{ $todo->todo }} <button href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</button>
   <hr>
@endforeach

@foreach($todos as $todo)
   {{ $todo->todo }} <a href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</a>
   <hr>
@endforeach

答案 2 :(得分:1)

您应该这样做:

删除按钮:

 <a class="btn btn-primary" href="{{ route('todo.delete',$todo->id) }}">Delete</a>

删除功能如下:

public function delete($id) {
    try {
        $delete_flag = Todo::where(['id' => $id])->first();
        $delete_flag->delete();
        return redirect()->back()->with('success', 'Todo deleted successfully');
    } catch (Exception $ex) {
        return redirect()->back()->with('error', 'Something went wrong');
    }
}

答案 3 :(得分:1)

@foreach($todos as $todo)
   {{ $todo->todo }} <a href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</a>

@endforeach

delete code--
$toDo = Todo::findOrFail($id)->delete();
if($toDo){
   return response()->josn(['message'=>'deleted']);
}