I try to use updateOrCreate function in an observer. So i have this function :
$transportpropremoyenaller = Transport::updateOrCreate(
['centre_id' => $gestionsejour->centre_id, 'allerouretour' =>
'Aller', 'date' => $gestionsejour->datedebut],
['ville' => \Config::get('constants.transport.0'), 'tarif' => '0']
);
I use this function in GestionsejourObserver like that :
public function created(Gestionsejour $gestionsejour)
{
return $this->addtransportpropremoyen($gestionsejour);
}
When i create a new object updateOrCreate never update and always create a new one.
Gestionsejour model is:
protected $fillable = [
'datefin',
'user_id',
'agrement',
'centre_id',
'datedebut',
'created_at',
'updated_at',
'deleted_at',
'dureesejour',
'periodesejour',
'complet',
];
public function centre()
{
return $this->belongsTo(Centre::class, 'centre_id');
}
public function getDatedebutAttribute($value)
{
return $value ? Carbon::parse($value)->format(config('panel.date_format')) : null;
}
public function setDatedebutAttribute($value)
{
$this->attributes['datedebut'] = $value ? Carbon::createFromFormat(config('panel.date_format'), $value)->format('Y-m-d') : null;
}
public function getDatefinAttribute($value)
{
return $value ? Carbon::parse($value)->format(config('panel.date_format')) : null;
}
public function setDatefinAttribute($value)
{
$this->attributes['datefin'] = $value ? Carbon::createFromFormat(config('panel.date_format'), $value)->format('Y-m-d') : null;
}
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
Myabe it's not possible to send 3 attributes or there is a problem with date. I don't know. I'm reading laravel doc but don't understand what is the problem in this simple function.
I think your problems lies in this method getDatedebutAttribute
When you run the following piece of code, the accessor is also used, meaning you're searching for d-m-y format, visualised below.
'date' => $gestionsejour->datedebut // '03-08-2019' <- because of getDatedebutAttribute
Maybe you can create a helper mehtod instead of using accessors and mutators. Leaving the data on the model the same as inside your database. another thing you can do on your model is telling which columns are dates with $dates, so they will automatically be Carbon Objects
// Model.php
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'datedebut',
];
public function formattedDateDebut()
{
return $this->datedebut ? $this->datedebut->format('d-m-y') : null;
}
And use it inside your views like this.
{{ $gestionsejour->formattedDateDebut() }}
This way you also dont need the setDatedebutAttribute
anymore, because Y-m-d is the default format when you use it here 'date' => $gestionsejour->datedebut