Reputation: 9314
I'm having a little trouble working out how I can add a global scope to a route group in laravel. What I've done is
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");
});
The idea is that I want the public query to be added within the entire group! This includes calling newQuery on the salon model and route bindings. Is this possible like this? Suppose I'm being lazy and instead of defining a route binding and add the scope to every use I'd rather do it here as I need this binding throughout this group!
Thanks in advance :)
Upvotes: 2
Views: 2874
Reputation: 6335
Create a middleware to add the scope for the routes:
In app/Http/Kernel.php
:
protected $routeMiddleware = [
// Other route middleware
'restrict.public' => App\Http\Middleware\AddPublicScope::class
];
In your created 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);
}
}
Then in your route group definition:
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");
});
Upvotes: 5