Created
March 17, 2015 20:20
-
-
Save lukepolo/2e9e56fd98a2ab1265d8 to your computer and use it in GitHub Desktop.
Laravel 5 - Scope Example : By User
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
// Scope Interface | |
<?php | |
namespace App\Models\Scopes; | |
use Illuminate\Database\Eloquent\ScopeInterface; | |
use Illuminate\Database\Eloquent\Builder; | |
use Illuminate\Database\Eloquent\Model; | |
class ByUserScope implements ScopeInterface | |
{ | |
/** | |
* Apply the scope to a given Eloquent query builder. | |
* | |
* @param \Illuminate\Database\Eloquent\Builder $builder | |
* @param \Illuminate\Database\Eloquent\Model $model | |
* @return void | |
*/ | |
public function apply(Builder $builder, Model $model) | |
{ | |
if(class_exists('app') === true) | |
{ | |
$user = \App::make('user'); | |
$builder->where('user_id', '=', $user->id); | |
} | |
else | |
{ | |
$builder->where('user_id', '=', \Auth::user()->id); | |
} | |
} | |
} | |
// Trait | |
<?php | |
namespace App\Models\Traits; | |
use App\Models\Scopes\ByUserScope; | |
trait ByUser | |
{ | |
/** | |
* Boot the soft deleting trait for a model. | |
* | |
* @return void | |
*/ | |
public static function bootByUser() | |
{ | |
static::addGlobalScope(new ByUserScope); | |
} | |
} | |
// Model | |
<?php | |
namespace Modules\Absplit\Models; | |
use Illuminate\Database\Eloquent\Model; | |
class Absplit_Experiments extends Model { | |
use \App\Models\Traits\ByUser; | |
protected $guarded = [ | |
'id', | |
'absplit_experiment_type_id', | |
'absplit_experiment_settings_id' , | |
'absplit_experiment_data_id' | |
]; | |
public function data() | |
{ | |
return $this->hasOne('\Modules\Absplit\Models\Absplit_Experiment_Data'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment