Skip to content

Instantly share code, notes, and snippets.

@JordanDalton
Created September 23, 2017 21:29
Show Gist options
  • Save JordanDalton/9b291fa867df5972c5e5a2b66d4f5d42 to your computer and use it in GitHub Desktop.
Save JordanDalton/9b291fa867df5972c5e5a2b66d4f5d42 to your computer and use it in GitHub Desktop.
Here's an example of what do to if you desire to use Laravel's updateExistingPivot() while getting your attributes mutated through a pivot model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Employee extends Model
{
/**
* Return all the requirements that are assigned to the employee.
*
* @return BelongsToMany
*/
public function requirements() : BelongsToMany
{
return $this->belongsToMany(Requirement::class)
->withTimestamps()
->withPivot([
'completion_date',
])
->using(EmployeeRequirement::class);
}
}
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\Pivot;
class EmployeeRequirement extends Pivot
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'completion_date',
];
/**
* Convert a provide completion date to a standard date format.
*
* @param $date
*
* @return void
*/
public function setCompletionDateAttribute($date)
{
$this->attributes['completion_date'] = $date ? Carbon::parse($date)->toDateString() : null;
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Requirement extends Model
{
// Blah blah blah...
}
<?php
$attributes = [
'completion_date' => '11MAY13',
];
// Obtain the target employee and requirement record.
$employee = App\Employee::first();
$requirement = \App\Requirement::first();
// Attach the requriement to the employee. This will cause completion_date to be mutated to '2013-11-05' on insert.
$employee->requirements()->attach($requirement, $attributes);
# Now you decide you need to update the record.
// Under this scenario Laravel would attempt to inject 11MAY13 into the completion_date column which will break the database.
$employee->requirements()->updateExistingPivot($requirement->id, $attributes);
// Using this approach would allow your date to be mutated.
$employee->requirements()->updateExistingPivot($requirement->id, (new \App\EmployeeRequirement($attributes))->toArray());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment