自动为 Laravel 模型中的字段赋值

FeR*_*cHo 2 php laravel eloquent

我正在使用 laravel,在我的一个模型中,每次创建记录时,我都需要自动将值分配给一个字段(日期类型),因为我刚开始使用 laravel,我不这样做,因为我尝试带有突变器:

public function setApprovedDateAttribute($date)
{
    $this->attributes['approved_date'] = Carbon::now()->format('Y-m-d');
}
Run Code Online (Sandbox Code Playgroud)

但它对我不起作用,因为我认为 mutator 作为它的名字说它改变了我为此字段发送的值,在我的情况下,我每次创建新记录时都需要自动添加一个,那么如何我可以这样做吗?

Tpo*_*jka 8

正如@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');
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:我添加了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);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意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,

    ],
];
Run Code Online (Sandbox Code Playgroud)

所有这些都可以在boot()模型的方法中跳过和完成,但显示的方式对我来说更容易维护。