@m33ch Yes, it is possible to use mutators in pivot model but it will not affect relation methods, ie. sync, attach etc. since pivot model is never touched during these calls.
Mar 6, 2015
4
Level 1
Set/Get Date Mutator in Pivot
Hi all,
is it possible set date mutator in pivot relations? This is my tables structures :
foo :
- id
- title
bar :
- id
- title
foo_bar
- id
- foo_id
- bar_id
- start_date
- end_date
and related models:
Foo Model
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Foo extends Model {
public function bar()
{
return $this->belongsToMany('Bar 'foo_bar')->withPivot('start_date', 'end_date');
}
public function newPivot(\Illuminate\Database\Eloquent\Model $parent, array $attributes, $table, $exists)
{
return new FooBar($parent, $attributes, $table, $exists);
}
}
Bar Model :
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Bar extends Model {
public function foo()
{
return $this->belongsToMany('Foo 'foo_bar')->withPivot('start_date', 'end_date');
}
public function newPivot(\Illuminate\Database\Eloquent\Model $parent, array $attributes, $table, $exists)
{
return new FooBar($parent, $attributes, $table, $exists);
}
}
And FooBar Pivot
<?php namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Carbon\Carbon;
class FooBar extends Pivot {
public function getStartDateAttribute($value)
{
if ($value)
return Carbon::createFromFormat('Y-m-d', $value)->format('d/m/Y');
}
public function getEndDateAttribute($value)
{
if ($value)
return Carbon::createFromFormat('Y-m-d', $value)->format('d/m/Y');
}
public function setStartDateAttribute($value)
{
$this->attributes['start_date'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
}
public function setEndDateAttribute($value)
{
$this->attributes['end_date'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
}
}
Test :
$fooData1 = ['title' => 'foo test 1' ];
$foo1 = Foo::create($fooData1);
$fooData2 = ['title' => 'foo test 2' ];
$foo2 = Foo::create($fooData2);
$fooBar1 = [ 'start_date' => '20/03/2015', 'end_date' => '25/03/2015' ];
$fooBar2 = [ 'start_date' => '20/02/2015', 'end_date' => '25/02/2015' ];
$bar->foo()->sync( [$foo1->id => $fooBar1] );
$bar->foo()->sync( [$foo2->id => $fooBar2] );
Set date mutator not work!
Thanks!
Level 53
1 like
Please or to participate in this conversation.