简体   繁体   English

Laravel 5.2-从数据库删除

[英]Laravel 5.2 - Delete from db

I am using Laravel Framework version 5.2.45 . 我正在使用Laravel Framework version 5.2.45

I have created a simple view that outputs my todos: 我创建了一个简单的视图来输出待办事项:

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

    <hr>
@endforeach

Within my routes I have created the following route to delete a todo : 在我的路线中,我创建了以下路线以删除todo

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

Within my TodosController I created the following delete method: 在我的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();
    }
// ...

When I press the button in the frontend nothing happens. 当我按下前端的按钮时,什么也没发生。 I do not get any error... 我没有任何错误...

Any suggestions what is wrong with my implementation? 有什么建议我的实现有什么问题吗?

Appreciate your replies! 感谢您的答复!

Try Below code, You have used a button instead of a tag 尝试下面的代码,您已使用按钮而不是标签

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

            <hr>
        @endforeach

You are using button not tag 您正在使用按钮而非标签

turn your code from 从你的代码

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

to

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

You should do like this : 您应该这样做:

Delete Button : 删除按钮:

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

And delete function look like below : 删除功能如下:

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');
    }
}
@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']);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM