我的 laravel 8.0 應用程式中有以下路由組:
Route::prefix('offline_transaction')->name('offline_transaction.')->group(function () {
Route::post('/approve/{transaction:uuid}', [OfflineTransactionController::class, 'approve'])
->name('approve');
Route::post('/reject/{transaction:uuid}', [OfflineTransactionController::class, 'reject'])
->name('reject');
});
Transaction模型是:
class Transaction extends Model implements CreditBlocker
{
//....
protected static function boot()
{
parent::boot();
static::addGlobalScope(new AuthUserScope());
}
//....
}
這是我的AuthUserScope:
class AuthUserScope implements Scope
{
private string $fieldName;
public function __construct($fieldName = 'user_id')
{
$this->fieldName = $fieldName;
}
public function apply(Builder $builder, Model $model)
{
$user = Auth::user();
if ($user) {
$builder->where($this->fieldName, $user->id);
}
}
}
現在的問題是當管理員想要批準或拒絕時transaction,會拋出404 Not found錯誤。我怎么能通過這個?
uj5u.com熱心網友回復:
自定義決議邏輯
如果您想定義自己的模型系結決議邏輯,您可以使用該
Route::bind方法。您傳遞給該bind方法的閉包將接收 URI 段的值,并應回傳應注入路由的類的實體。同樣,這種定制應該在boot您的應用程式的方法中進行RouteServiceProvider:
解決方案
您可以做的是更改routes/web.php檔案中特定路由的引數名稱。
Route::prefix('offline_transaction')->name('offline_transaction.')->group(function () {
Route::post('/approve/{any_transaction}', [OfflineTransactionController::class, 'approve'])
->name('approve');
Route::post('/reject/{any_transaction}', [OfflineTransactionController::class, 'reject'])
->name('reject');
注意any_transaction. 將其更改為您認為最方便的任何命名約定。
然后,在您的app/Providers/RouteServiceProvider.php檔案中,將您的boot(...)方法更改為如下所示:
use App\Models\Transaction;
use Illuminate\Support\Facades\Route;
// ...
public function boot()
{
// ...
Route::bind('any_transaction', function($uuid) {
return Transaction::withoutGlobalScopes()->where('uuid', $uuid)->firstOrFail();
});
// ...
}
// ...
然后在你的控制器app/Http/Controllers/OfflineTransactionController.php檔案中,訪問注入的模型:
use App\Models\Transaction;
// ...
public function approve(Transaction $any_transaction) {
// ...
}
// ...
致謝:使用沒有全域范圍的路由模型系結 @thomaskim
附錄
如果您想從路由模型系結查詢中洗掉特定的全域范圍,您可以
withoutGlobalScope(AuthUserScope::class)在檔案的boot(...)方法中使用app/Providers/RouteServiceProvider.php。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/422367.html
標籤:
上一篇:獲取關系表資料為空
下一篇:如何在資源中創建列別名
