Skip to content

Instantly share code, notes, and snippets.

@elomatreb
Created February 14, 2016 19:04
Show Gist options
  • Save elomatreb/66cc58e760e73a08ac6f to your computer and use it in GitHub Desktop.
Save elomatreb/66cc58e760e73a08ac6f to your computer and use it in GitHub Desktop.
A simple trait for Eloquent models that provides convenience filters and methods for checking ownership
<?php
namespace App\Traits;
use App\User;
/**
* A model that is owned by a user
*/
trait OwnedModelTrait
{
/**
* Get the owner of the model
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo("App\User");
}
/**
* Check if the model is owned by the given user. Does not check for existence of user
*
* @param \App\User|int $user The user instance or user ID
*
* @throws \InvalidArgumentException If the provided argument is neither a user ID
* nor a User instance
*
* @return bool
*/
public function isOwnedBy($user): bool
{
if (! self::isUserOrUserId($user)) {
throw new \InvalidArgumentException(sprintf(
"isOwnedBy() expected User instance or ID, got %s",
is_object($user) ? get_class($user) : gettype($user)
));
}
return ($this->user_id === (is_int($user) ? $user : $user->id));
}
/**
* Filter models by owner. Does not check for existence of user
*
* @throws \InvalidArgumentException If the provided argument is neither a
* valid user ID (greater than 0) nor a User instance
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeOwnedBy($query, $user)
{
if (! self::isUserOrUserId($user)) {
throw new \InvalidArgumentException(sprintf(
"scopeOwnedBy() expected User instance or ID, got %s",
is_object($user) ? get_class($user) : gettype($user)
));
}
return $query->where("user_id", "=", is_int($user) ? $user : $user->id);
}
/**
* Utility method to check if a given argument is a user instance or a user ID
*
* @param mixed $user The object to check
*
* @return bool True if the parameter is a integer greater than 0 or a User instance
*/
private static function isUserOrUserId($user): bool
{
return ($user instanceof User || (is_int($user) && $user > 0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment