Skip to content

Instantly share code, notes, and snippets.

@bericp1
Created January 9, 2019 02:34
Show Gist options
  • Save bericp1/4e960f807fcb2751ef5cba7bdcf75459 to your computer and use it in GitHub Desktop.
Save bericp1/4e960f807fcb2751ef5cba7bdcf75459 to your computer and use it in GitHub Desktop.
A Laravel model abstraction for models whose relationships or dynamic attributes should be current-user-aware. A little better than using global scope (i.e. `\Auth::user();`) but not much better.
<?php
namespace App\Support;
use App\User;
use Illuminate\Database\Eloquent\Model;
abstract class CurrentUserAwareModel extends Model
{
/**
* @var \App\User
*/
protected static $currentUser = null;
/**
* Gets the current user that the model is aware of.
*
* @return \App\User|null
*/
protected static function getCurrentUser()
{
return static::$currentUser;
}
/**
* Make the model aware of the current user.
*
* @param \App\User $user
*/
protected static function setCurrentUser(User $user)
{
static::$currentUser = $user;
}
/**
* Make the model forget the current user.
*/
protected static function forgetCurrentUser()
{
static::$currentUser = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment