我有一个包含timestamp
的一些属性的表,这个表包含关于发票的字段,当用户第一次输入invoice
值为不正确的形式时,我想在24 hours
添加项目后仅在一段时间内更改发票中的值!!当发票超过24 hours
时,我想防止他做任何更改,我使用laravel框架
在您的发票模型中,您需要添加一个受保护的$timestamp设置为true;
当一个记录被创建或更新时,字段created_at/updated at将被自动填充。
所以在laravel中有一个包含的功能来处理日期时间是一个叫做Carbon的库
正如tadman和Khalid在控制器中建议的,你可以这样做:
<?php
namespace App'Http'Controllers;
use Carbon'Carbon;
use Invoice;
class FooInvoiceController extends Controller
{
/**
*
* Method to check if invoice is editable
*
* @param $invoiceId
* @return bool
*/
public function isInvoiceEditable($invoiceId)
{
$now = Carbon::now();
$invoiceCreatedAt = Invoice::where('id', $invoiceId)->get()->created_at;
$diffInHours = Carbon::parse($invoiceCreatedAt);
$length = $diffInHours->diffInHours($now);
if ($length > 24) {
return false;
}
return true;
}
/**
* @param $invoiceId
*/
public function fooAction($invoiceId)
{
if ($this->isInvoiceEditable($invoiceId)) {
// Work here
}
}
}
您可以通过不同的方式执行此业务规则:
- 如果你的应用程序中的所有更新都通过Http发生,那么你可以在你的控制器中处理它
class InvoiceController extends Controller
{
// ...
public function update($id, Request $request)
{
$invoice = Invoice::findOrFail($id);
abort_if($invoice->created_at < Carbon::now()->subHours(24),
422, "Updating is no longer available.");
// proceed as ussual (validate, save, fire events, etc)
}
// ...
}
- 您还可以通过监听
updating
事件并在更新周期过期时返回false
,使模型本身强制执行此规则,这将阻止为模型保存更改。class Invoice extends Model { // ... public static function boot() { parent::boot(); self::updating(function ($model) { return $model->created_at !== null && $model->created_at >= Carbon::now()->subHours(24); }); } // ... }
如果您必须选择哪些属性可以或不可以更新,您可以为每个受保护的属性实现单独的mutator,并在更新周期过期时抛出异常。
根据你正在使用的数据库,你可以潜在地处理数据库级别的触发器