Skip to content

Instantly share code, notes, and snippets.

@alexweissman
Last active February 12, 2017 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexweissman/ab30db5fc66567439b2d5be933d5c942 to your computer and use it in GitHub Desktop.
Save alexweissman/ab30db5fc66567439b2d5be933d5c942 to your computer and use it in GitHub Desktop.
<?php
namespace UserFrosting\Sprinkle\ExtendUser\Model;
use Illuminate\Database\Capsule\Manager as Capsule;
use UserFrosting\Sprinkle\Account\Model\User;
use UserFrosting\Sprinkle\ExtendUser\Model\Owler;
class OwlerUser extends User {
protected $fillable = [
"user_name",
"first_name",
"last_name",
"email",
"locale",
"theme",
"group_id",
"flag_verified",
"flag_enabled",
"last_activity_id",
"password",
"deleted_at",
"city",
"country"
];
/**
* Required to be able to access the `owler` relationship in Twig without needing to do eager loading.
* @see http://stackoverflow.com/questions/29514081/cannot-access-eloquent-attributes-on-twig/35908957#35908957
*/
public function __isset($name)
{
if (in_array($name, [
'owler'
])) {
return isset($this->owler);
} else {
return parent::__isset($name);
}
}
/**
* Custom accessor for Owler property
*/
public function getCityAttribute($value)
{
return (count($this->owler) ? $this->owler->city : '');
}
/**
* Custom accessor for Owler property
*/
public function getCountryAttribute($value)
{
return (count($this->owler) ? $this->owler->country : '');
}
/**
* Get the owler associated with this user.
*/
public function owler()
{
return $this->hasOne('\UserFrosting\Sprinkle\ExtendUser\Model\Owler', 'user_id');
}
/**
* Custom mutator for Owler property
*/
public function setCityAttribute($value)
{
$this->createRelatedOwlerIfNotExists();
$this->owler->city = $value;
}
/**
* Custom mutator for Owler property
*/
public function setCountryAttribute($value)
{
$this->createRelatedOwlerIfNotExists();
$this->owler->country = $value;
}
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
error_log("Hey I'm bootin here");
/**
* Create a new instance, and also create a related Owler object.
*/
static::created(function ($owlerUser) {
error_log("In created event handler");
Capsule::transaction( function() use ($owlerUser) {
$owlerUser->owler()->create($owlerUser->getAttributes());
});
});
static::saved(function ($owlerUser) {
error_log("Saving related owler");
$owlerUser->owler->save();
});
}
protected function createRelatedOwlerIfNotExists()
{
if (!count($this->owler)) {
error_log("No owler found for user " . $this->id);
$owler = new Owler([
'user_id' => $this->id
]);
$this->setRelation('owler', $owler);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment