Reputation: 1151
I am working with laravel and in one of my models I need to automatically assign the value to a field (of type date) every time a record is created, as I am just starting with laravel, I do not do this, since I try with a mutator:
public function setApprovedDateAttribute($date)
{
$this->attributes['approved_date'] = Carbon::now()->format('Y-m-d');
}
but it doesn't work for me, because I think that the mutator as its name says it changes the value that I am sending for this field, in my case I need to add one automatically every time I create a new record, so how can I do this?
Upvotes: 2
Views: 2947
Reputation: 7111
As @apokryfos mentioned in comment, best would be do it over creating event.
Here what you should do, let's say your table is subscriptions
with field subscriptions.approved_date
and model is Subscription
, here is very clean way of what you can do to achieve issued result:
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');
}
}
Note: I added creating()
method, it isn't there by default.
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);
}
}
Notice line in boot()
method.
3.
Include provider into provider list of 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,
],
];
All this can be skipped and done in boot()
model's method but shown way is easier to maintain for me.
Upvotes: 9