Created
January 9, 2019 02:34
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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