[英]Will Model::updateOrCreate() update a soft-deleted model if the criteria matches?
[英]Let show method of resource controller to show soft-deleted model using policy
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
model 中添加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- 在数据库中创建一个项目和 go 到 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");
});
model被软删除,如何在GET /items/1
中进入show方法?
笔记
确保您已登录
我已经检查了这个问题,但我无法让它工作
我还尝试将 controller 中的显示方法更改为这种方式( $id
而不是Item $item
),但无论如何我得到 404。我没有进入该方法,政策在中间并且不让我进入:
public function show($id)
{
dd($id);
// dd($item);
}
就像在routes/web.php
文件中定义的路由资源路由的末尾添加withTrashed()
function 一样简单。
前:
Route::resource('items', ItemController::class);
后:
Route::resource('items', ItemController::class)->withTrashed(['show']);
在我的一个较旧的项目中,尽管做了上面解释的,我还是收到了这个错误:
Method Illuminate\Routing\PendingResourceRegistration::withTrashed does not exist.
我通过更新项目的 composer pagackes 解决了这个问题:
composer update
现在工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.