laravel 让资源控制器显示方法来显示使用策略的软删除模型

nhaq1z21  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(141)

重现我面临的问题的步骤

1-创建项目:

php artisan make:model Item --all

2-在web.php中创建资源:

Route::resource('items', ItemController::class);

3-然后,在ItemController的构造函数中,链接ItemPolicy

public function __construct()
{
    $this->authorizeResource(Item::class);
}

4-在ItemPolicy的所有方法中返回true(这样您就获得了授权)

public function view(User $user, Item $item)
{
    return true;
}

5-在Item模型中添加SoftDeletes特征:

namespace App\Models;

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

class Item extends Model
{
    use HasFactory, SoftDeletes;
}

6-在项目迁移中添加SoftDeletes。运行它。

public function up()
{
    Schema::create('items', function (Blueprint $table) {
        $table->id();
        $table->timestamps();

        $table->softDeletes();
    });
}

7-在ItemController中的show方法中写入一个dd,以检查您是否确实在方法中输入了:

public function show(Item $item)
{
    dd('You are inside the show function');
}

8-在数据库中创建一个项目,然后转到GET /items/1。您应该看到dd消息。

Route::get('/testCreate', function () {
    $item = Item::create();

    return redirect("/items/$item->id");
});

9-现在,在GET /items/1中,消息不再出现(相反,我得到404)。

Route::get('/testDelete', function () {
    $item = Item::firstOrFail();

    $item->delete();

    return redirect("/items/$item->id");
});

问题

如何在模型被软删除的情况下在GET /items/1中输入show方法?

备注

  • 确保您已登录
  • 我已 checkout this question,但无法使用
  • 我还尝试将控制器中的show方法更改为这种方式($id而不是Item $item),但无论如何我得到404。我没有进入该方法,策略在中间,不允许我进入:
public function show($id)
{
    dd($id);
    // dd($item);
}
xlpyo6sf

xlpyo6sf1#

这就像在routes/web.php文件中定义的路径资源路径的末尾添加withTrashed()函数一样简单。
之前:

Route::resource('items', ItemController::class);

之后:

Route::resource('items', ItemController::class)->withTrashed(['show']);

相关文档请单击此处和此处。

更新

在一个旧的项目,我有,尽管做上面解释,我得到这个错误:

Method Illuminate\Routing\PendingResourceRegistration::withTrashed does not exist.

我通过更新项目的 composer pagackes来解决这个问题:

composer update

现在工作正常。

相关问题