我在解决如何将全局范围添加到laravel中的路由组时遇到了一些麻烦。我所做的是
Route::group([
"prefix" => "customer",
"namespace" => "Customer",
"as" => "Customer.",
], function() {
//make sure only public salons are displayed!
\App\Salon::addGlobalScope("public", function(\Illuminate\Database\Eloquent\Builder $builder) {
$builder->where("public", 1);
});
Route::get("/", "IndexController@index")->name("index");
Route::get("/salon/{salon}", "SalonController@show")->name("salon.show");
});
我的想法是希望在整个组中添加公共查询!这包括在沙龙模型和路由绑定上调用newQuery。这样可能吗?假设我是懒惰的,而不是定义路由绑定并将范围添加到每个用途我宁愿在这里做,因为我需要在整个组中进行绑定!
提前致谢:)
答案 0 :(得分:4)
创建中间件以添加路由范围:
在app/Http/Kernel.php
:
protected $routeMiddleware = [
// Other route middleware
'restrict.public' => App\Http\Middleware\AddPublicScope::class
];
在您创建的app/Http/Middleware/AddPublicScope.php
:
namespace App\Http\Middleware;
use Closure;
use App\Salon;
use Illuminate\Database\Eloquent\Builder;
class AddPublicScope
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
Salon::addGlobalScope('public', function($builder) {
$builder->where('public', 1);
});
return $next($request);
}
}
然后在您的路线组定义中:
Route::group([
"prefix" => "customer",
"namespace" => "Customer",
"middleware" => ['restrict.public']
"as" => "Customer.",
], function() {
Route::get("/", "IndexController@index")->name("index");
Route::get("/salon/{salon}", "SalonController@show")->name("salon.show");
});