Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dangnhdev/adf789020d6b879cb5c5ad287073fa4b to your computer and use it in GitHub Desktop.
Save dangnhdev/adf789020d6b879cb5c5ad287073fa4b to your computer and use it in GitHub Desktop.
Throw exception on Eloquent model binding name mismatch
<?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