首页 > 解决方案 > 如何在 Laravel 中删除一个类别

问题描述

我打算在我的数据库中删除一个类别,我已经通过使用 Livewire 组件成功地做到了这一点,但我试图通过使用控制器来实现它。这是我的 Controller.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Brian2694\Toastr\Facades\Toastr;
use App\Models\Staff;
use App\Models\User;
use App\Models\Category;
use Livewire\WithPagination;
use Haruncpi\LaravelIdGenerator\IdGenerator;
use DB;

class CategoriesController extends Controller
{
    use WithPagination;
    public function deleteCategory($id)
    {
$category = Category::find($id);
$category->delete();
session()->flash('message', 'Category has been deleted successfully !');
    }
    public function index()
    {
        $categories = Category::paginate(10);

        return view('form.categories', ['categories' => $categories]);
    }
}

在这里我有一个刀片(不是 Livewire 的):

@foreach ($categories as $category)
               <tr>
                      <td>{{$category->id}}</td>
                      <td>{{$category->name}}</td>
                      <td>{{$category->slug}}</td>
                      <td>
                      <a href="{{route('admin.editcategory', ['category_slug'=> $category->slug])}}"><i class="fa fa-edit "></i></a>
                      <a href="#" onclick="confirm('Are you sure ,You want to delete this Category ?') || event.stopImmediatePropagation()" wire:click.prevent="deleteCategory({{$category->id}})"><i class="fa fa-times  text-danger"></i></a>
                      </td>
               </tr>
               @endforeach

标签: phpdatabaselaravel

解决方案


如果您想在控制器中执行此操作,则应该有一个链接,而不是将其视为仍然是一个LiweWire组件并直接调用该方法。该route()调用将生成您需要的 URL,并让您的标签链接到该路由。

<a href="{{route('category.delete', $category->id)}}" onclick="confirm('Are you sure ,You want to delete this Category ?') || event.stopImmediatePropagation()">
     <i class="fa fa-times  text-danger"></i>
</a>

为此,您需要一条路线来实际触发您的删除方法。在web.php路线文件中添加该路线。

Route::get('category/delete/{id}', [CategoriesController ::class, 'deleteCategory']);

为了用户体验,我会在删除后重定向回来。

public function deleteCategory($id)
{
    $category = Category::find($id);
    $category->delete();
    session()->flash('message', 'Category has been deleted successfully !');

    return redirect()->back();
}

意识到

我不会认为这种方法是最好的解决方案,通常你会在Http调用时使用 DELETE 方法进行删除操作。由于这似乎是您进入控制器的第一步,我认为这会很好,就像在Http需要表单中执行 DELETE 方法一样。


推荐阅读