正如@apokryfos 在评论中提到的那样,最好是通过创建事件来完成。
这里你应该做什么,假设你的表是subscriptions,字段为subscriptions.approved_date,模型是Subscription,这是实现发布结果的非常干净的方法:
1。
php artisan make:observer SubscriptionObserver --model=Subscription
<?php
namespace App\Observers;
use App\Subscription;
use Carbon\Carbon;
class SubscriptionObserver
{
/**
* Handle the subscription "creating" event.
*
* @param Subscription $subscription
* @return void
*/
public function creating(Subscription $subscription)
{
$subscription->approved_date = Carbon::now()->format('Y-m-d');
}
}
注意:我添加了creating()方法,默认不存在。
2。
php artisan make:provider SubscriptionServiceProvider
<?php
namespace App\Providers;
use App\Observers\SubscriptionObserver;
use App\Subscription;
use Illuminate\Support\ServiceProvider;
class SubscriptionServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
Subscription::observe(SubscriptionObserver::class);
}
}
boot() 方法中的注意行。
3。
将提供者包含到config/app.php 的提供者列表中
<?php
return [
// other elements
/*
|------------------------------
| Autoloaded Service Providers
|------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
// other providers
App\Providers\SubscriptionServiceProvider::class,
],
];
所有这些都可以在boot()模型的方法中跳过和完成,但显示的方式对我来说更容易维护。