diff --git a/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php b/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php index 19dc16416746..0025ece8e7e7 100644 --- a/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php +++ b/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php @@ -80,24 +80,37 @@ protected function normalizeGuessedAbilityName($ability) * @param \Illuminate\Http\Request|null $request * @return void */ + public function authorizeResource($model, $parameter = null, array $options = [], $request = null) { $model = is_array($model) ? implode(',', $model) : $model; - $parameter = is_array($parameter) ? implode(',', $parameter) : $parameter; - $parameter = $parameter ?: Str::snake(class_basename($model)); - $middleware = []; + $request = $request ?: request(); + + // Getting the current action method from the request + $currentMethod = $request->route()->getActionMethod(); - foreach ($this->resourceAbilityMap() as $method => $ability) { - $modelName = in_array($method, $this->resourceMethodsWithoutModels()) ? $model : $parameter; + // Determine if the current method should be processed based on 'only' or 'except' options + if (isset($options['only']) && !in_array($currentMethod, (array) $options['only'])) { + return; // Skip authorization if not in 'only' list + } - $middleware["can:{$ability},{$modelName}"][] = $method; + if (isset($options['except']) && in_array($currentMethod, (array) $options['except'])) { + return; // Skip authorization if in 'except' list } - foreach ($middleware as $middlewareName => $methods) { - $this->middleware($middlewareName, $options)->only($methods); + // Get the ability corresponding to the current method + $ability = $this->resourceAbilityMap()[$currentMethod] ?? null; + + // Check if there is an ability defined for the current method + if ($ability) { + // Decide the model or parameter to authorize against + $modelName = in_array($currentMethod, $this->resourceMethodsWithoutModels()) ? $model : array_values(array_intersect_key($request->route()->parameters, array_flip((array) $parameter))); + + // Perform the authorization check + app(Gate::class)->authorize($ability, $modelName); } }