Php 特定路线和it的Laravel全球范围';s支线

Php 特定路线和it的Laravel全球范围';s支线,php,laravel,Php,Laravel,假设有这样一个测试模型: class Test extends Model { public $primaryKey = 'test_id'; public function questions () { return $this->belongsToMany('App\Question', 'question_test', 'test_id', 'question_id')->withPivot('weight

假设有这样一个
测试
模型:

class Test extends Model
{
        public $primaryKey = 'test_id';
        public function questions ()
        {
            return $this->belongsToMany('App\Question', 'question_test', 'test_id', 'question_id')->withPivot('weight');
        }
}
还有这样一个
问题
模型:

class Question extends Model
{
        public $primaryKey = 'question_id';
        public function tests ()
        {
            return $this->belongsToMany('App\Test', 'question_test', 'question_id', 'test_id')->withPivot('weight');
        }
}
问题模型字段如下所示:

question_id
text
correct
active  => can be true or false
created_at
updated_at
http://myapp.dev/Admin/tests
http://myapp.dev/Admin/test/5/questions
http://myapp.dev/Admin/test/5/question/create
http://myapp.dev/Admin/test/5/remove
正如您所见,这两个模型之间存在着大量的关系

在我的应用程序中,我有两个独立的部分,一个用于管理员用户,另一个用于公共用户

管理员可以对问题和测试执行任何操作。比如在测试中添加一些问题,删除,编辑等等

但在另一方面,公共用户只能测试和相关的问题是活跃的(意味着他们的活跃领域是真实的)

假设一些管理路由是:

question_id
text
correct
active  => can be true or false
created_at
updated_at
http://myapp.dev/Admin/tests
http://myapp.dev/Admin/test/5/questions
http://myapp.dev/Admin/test/5/question/create
http://myapp.dev/Admin/test/5/remove
一些用户路线是:

http://myapp.dev/Dashboard
http://myapp.dev/tests-list
http://myapp.dev/test/5/questions
为此,我知道我可以在
问题
模型中这样使用:

public function scopeActive($query)
{
    return $query->where('active', 1);
}
当我只想获取活动问题时,必须这样做:

$test->questions->active()->get();
但是我有很多操作是在用户面板上执行的,因此如果想使用
active()
方法来选择问题,这是很困难和耗时的

我不能使用全局范围,因为这会影响整个项目中运行的所有问题查询

是否有一种方法可以定义公共用户可以看到的某些特定路由和子路由的全局(或本地)范围

还是有其他方法来解决这个问题

更新:


除了上面提到的那些,用户还可以有一些角色。例如,管理员用户可以从管理员面板切换到用户面板。在这种情况下,当他在用户面板上时,我只想显示活动的问题。

您可以通过在中间件中包装路由来实现这一点。通过运行
php artisan make:middleware HideInactiveQuestions创建HideInactiveQuestions.php

<?php

namespace App\Http\Middleware;

use App\Question;
use Closure;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class HideInactiveQuestions
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        Question::addGlobalScope('active', function(Builder $builder) {
            $builder->where('active', '=', 1);
        });

        return $next($request);
    }
}
现在,这些被这个中间件(restrict.public)包装的路由将被您的作用域过滤