Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save janzikmund/84df3c59cffe073a8cad3922e88295ff to your computer and use it in GitHub Desktop.
Save janzikmund/84df3c59cffe073a8cad3922e88295ff to your computer and use it in GitHub Desktop.
Allow composite key for eloquent model
<?php
ContentBlock::updateOrCreate([
'alias' => $key,
'section' => $section_snake,
], [
'content' => $val,
]);
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class ContentBlock extends Model
{
// if set it doesn't allow keyBy() called on collection. And still the key is composite so we have to search by two params manually anyway
//protected $primaryKey = 'alias';
protected $fillable = ['content', 'alias', 'section'];
/**
* Set the composite keys for a save update query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function setKeysForSaveQuery(Builder $query)
{
$query
->where('alias', '=', $this->getAttribute('alias'))
->where('section', '=', $this->getAttribute('section'));
return $query;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment