Answer the question
In order to leave comments, you need to log in
How to make it so that the global scope is applied when binding the route (and throws an error)?
There was a task - to make sure that certain elements by the criterion were not available through certain API routes. I decided to do it by applying a global scope to models, I wrote middleware:
<?php
namespace App\Http\Middleware;
use App\Models\Order;
use Closure;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
class AddApiScopes
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
Order::addGlobalScope('active', function (Builder $builder) {
$builder->where('status', '<>', 0);
});
return $next($request);
}
}
Route::prefix('/')->middleware(AddApiScopes::class)->group(function () {
//...
Route::get('orders', [ApiController::class, 'orders']);
Route::get('orders/{order}', [ApiController::class, 'order']);
//...
});
public function orders()
{
return OrderResource::collection(Order::all()); // тут скоуп применяется
}
public function order(Order $order)
{
if ($order->status === 0) { // костыль
abort(404);
}
return new OrderResource($order);
}
Route::get('test/{order_id}', function ($order_id) { // выдает 404
$order = Order::findOrFail($order_id);
return $order;
});
Route::get('test2/{order}', function (Order $order) { // выдает данные модели
return $order;
});
Answer the question
In order to leave comments, you need to log in
Need to substitute my middleware before
\Illuminate\Routing\Middleware\SubstituteBindings::class
in priorities: Crap decision. It seems to me better to register the apiOrder or activeOrder parameter and make the necessary request in the service provider.
For example
Route::bind('activeOrder', function ($value) {
return Order::active()->firstOrFail();
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question