-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathUsedByTeams.php
More file actions
67 lines (58 loc) · 1.42 KB
/
UsedByTeams.php
File metadata and controls
67 lines (58 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php namespace Mpociot\Teamwork\Traits;
/**
* This file is part of Teamwork
*
* @license MIT
* @package Teamwork
*/
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
/**
* Class UsedByTeams
* @package Mpociot\Teamwork\Traits
*/
trait UsedByTeams
{
/**
* Boot the global scope
*/
protected static function bootUsedByTeams()
{
static::addGlobalScope('team', function (Builder $builder) {
static::teamGuard();
$builder->where('team_id', auth()->user()->currentTeam->getKey());
});
static::saving(function (Model $model) {
static::teamGuard();
if (!isset($model->team_id)) {
$model->team_id = auth()->user()->currentTeam->getKey();
}
});
}
/**
* @param Builder $query
* @return mixed
*/
public function scopeAllTeams(Builder $query)
{
return $query->withoutGlobalScope('team');
}
/**
* @return mixed
*/
public function team()
{
return $this->belongsTo(Config::get('teamwork.team_model'));
}
/**
* @throws Exception
*/
protected static function teamGuard()
{
if (auth()->guest() || !auth()->user()->currentTeam) {
throw new Exception('No authenticated user with selected team present.');
}
}
}