php - 如何在 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
解决方案
如果您想在控制器中执行此操作,则应该有一个链接,而不是将其视为仍然是一个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 方法一样。
推荐阅读
- javascript - 如何在 Input 中设置值并选择
- c++ - 替代获取标准库函数的地址/可能是格式错误的行为
- javascript - 创建一个数组,其中包含对特定数字求和所需的数字
- python - 使用 PIL (python) 将图像数据集加载到内存中会消耗太多内存
- php - 使用 PHP 检查 SSL 证书哈希
- c - scanf("%d/%d/%d) 在 C 中是什么意思?
- flutter - 如何在 Flutter 中访问 GridView 中特定项目的索引?
- javascript - 使用 react redux 探针获取异步数据
- php - 如何解决贪婪的正则表达式
- python-2.7 - 我的 Logger 对象正在发送两条消息而不是一条