【问题标题】:Laravel resource destroy mtehode does not workLaravel 资源销毁 mtehode 不起作用
【发布时间】:2021-11-25 20:08:08
【问题描述】:

我用php artisan make:controller ProductController --resource 创建了一个产品资源控制器。并拥有所有必要的方法:索引、显示、更新和销毁。

我使用的是 Laravel 8,destroy 方法默认使用 Product $product 作为参数(路由模型绑定)。

理论上,我只需要取出产品对象并删除它?我还得到了状态码 200 和一个 true。然而,该条目并未从数据库中删除。

注意:我将路由键名称更改为 ID,将索引键名称更改为 uid 而不是 id。请参阅迁移和模型。

问题:为什么?我缺少什么?跟更改的路由键名有关系吗?

这是我的 ProductController、模型、迁移和路由:

ProductController.php -> destroy() 方法


    /**
     * Remove the specified resource from storage.
     *
     * @param \App\Models\Product $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        $result = $product->delete();
        return response()->json([
            'status' => $result,
            'msg' => $result ? 'success' : 'failed'
        ]);        
    }

型号\产品

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'ID',
        'name',
        'price',
    ];

    public function getRouteKeyName()
    {
      return 'ID';
    }    
}

产品迁移 up() 方法

    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('uid'); // changed
            $table->integer('ID')->unique(); // my new Route Key Name
            $table->string('name')->nullable();
            $table->integer('price')->nullable();
            $table->timestamps();
        });
    }

路由 api.php

Route::resource('products', App\Http\Controllers\ProductController::class);

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    你可以试试这个

    public function destroy($id)
    {
        $result = Post::where('ID', $id)->delete();
        return response()->json([
            'status' => $result,
            'msg' => $result ? 'success' : 'failed'
        ]);        
    }
    

    【讨论】:

    • 那行得通。但我想使用 Route Model 绑定的强大功能?因为 Laravel 已经把它作为 destroy 方法的参数。这可能是一个错误吗?
    • 路由模型绑定可能只是自动递增 id。如果您使用 id,则此方法有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 2021-06-01
    • 1970-01-01
    • 2017-12-18
    • 2016-07-23
    • 2018-09-06
    • 2018-01-16
    相关资源
    最近更新 更多