I am use OctoberCMS Rainlab.User plugin to manage authentication.
I have various models and that belongTo User.
How do i set up an anonymous global scope on each model to only return the records that belong to the authenticated user?
Many thanks in advance for any help.
use Auth;
protected static function booted()
{
$user = Auth::getUser();
static::addGlobalScope('user_id', function (Builder $builder){
$builder->where('user_id', $user);
});
}
I would create a dynamic scope in the model's definition page. You can read more about it here.
class PluginModel extends Model
{
/**
* Scope a query to only records with user.
*/
public function scopeGetUserRecords($query, $userId)
{
return $query->where('user_id', $userId);
}
}
Now any time you call your PluginModel class you can just do this:
$userRecords = PluginModel::getUserRecords($user->id)->get();