-
-
Save dangnhdev/adf789020d6b879cb5c5ad287073fa4b to your computer and use it in GitHub Desktop.
Throw exception on Eloquent model binding name mismatch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespaced App\Providers; | |
use RuntimeException; | |
use Illuminate\Support\Facades\Route; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Routing\ImplicitRouteBinding; | |
class RouteServiceProvider extends ServiceProvider | |
{ | |
/** | |
* Bootstrap routes and bindings. | |
*/ | |
public function boot(): void | |
{ | |
Route::substituteImplicitBindingsUsing(function ($container, $route) { | |
ImplicitRouteBinding::resolveForRoute($container, $route); | |
foreach ($route->signatureParameters(['subClass' => Model::class]) as $parameter) { | |
if (! $parameter->isDefaultValueAvailable() && ! $route->parameter($parameterName = $parameter->getName())) { | |
$modelName = Str::camel( | |
class_basename($parameter->getType()->getName()) | |
); | |
throw new RuntimeException( | |
"Route parameter name '{$parameterName}' does not match " | |
. "expected model binding name '{$modelName}'." | |
); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment