简体   繁体   English

获取 controller 中的删除 id 以删除 mysql 记录

[英]Get delete id in controller to delete mysql record

I have this in AuthController:我在 AuthController 中有这个:

public function DelFunc() {

    if(Auth::check() === true) {
        $deleted = DB::delete('delete from funcionarios where id = ?',[$id]);
    }
    return redirect()->route('admin.login');
}

But I get this error: Undefined variable: id但我收到此错误:未定义变量:id

I have this button in my view:我的视图中有这个按钮:

<a href="../admin/delFunc?id={{$empresa->id}}">
    <button class="btn btn-primary">Delete</button>
</a>

I know my question is simple, but, how can I get the id value on AuthController to delete this record?我知道我的问题很简单,但是,如何获取 AuthController 上的 id 值来删除这条记录?

I also have this route:我也有这条路线:

Route::get('/admin/delFunc', [App\Http\Controllers\AuthController::class, 'delFunc'])->name('delFunc');

A bunch of red flags here:这里有一堆危险信号:

  • Why is this going into a controller called AuthController when it is working with a Funcionario object?为什么当它与Funcionario object 一起工作时,它会进入名为AuthController的 controller?
  • Why direct database queries instead of using Eloquent models?为什么直接数据库查询而不是使用 Eloquent 模型?
  • You should not be deleting items by GET method, this is very dangerous.您不应该通过 GET 方法删除项目,这是非常危险的。
  • Authentication is to be done by middleware, not by checking within every controller method.身份验证由中间件完成,而不是通过检查每个 controller 方法。
  • And last, your method should also have a more conventional name like destroy .最后,您的方法还应该有一个更传统的名称,例如destroy

Route parameters are defined in the route definition with braces like "/admin/delete/{func}" and then bound to objects in the controller method definition.路由参数在路由定义中使用“/admin/delete/{func}”等大括号定义,然后绑定到 controller 方法定义中的对象。

So, putting all that together, what it should look like is:所以,把所有这些放在一起,它应该是这样的:

<?php

use App\Http\Controllers\FuncionarioController;
use Illuminate\Support\Facades\Route;

Route::middleware("auth")->group(function ($router) {
    $router->delete('/funcionario/{func}', [FuncionarioController::class, 'destroy'])
        ->name('funcionario.destroy');
});

And then in your controller:然后在您的 controller 中:

<?php

namespace App\Http\Controllers;

use App\Models\Funcionario;

class FuncionarioController extends Controller {

    public function destroy(Funcionario $func)
    {
        $func->delete();
        return redirect()
            ->route('admin.login')
            ->with('success', __('Funcionario deleted'));
    }
}

And your view would look like this, assuming your value is passed in the $id variable:假设您的值在$id变量中传递,您的视图将如下所示:

<form method="post" action="{{ route("funcionario.destroy", $id) }}">
    @method('DELETE')
    @csrf
    <button type="submit">{{ __("Delete") }}</button>
</form>

Instead of [$id] use [request('id')]而不是[$id]使用[request('id')]

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

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