Skip to content

Instantly share code, notes, and snippets.

@stevebauman
Last active May 14, 2024 02:19
Show Gist options
  • Save stevebauman/3d40e1760981ec01a3a70bdc0969aae8 to your computer and use it in GitHub Desktop.
Save stevebauman/3d40e1760981ec01a3a70bdc0969aae8 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}'."
);
}
}
});
}
}
@kareeminator
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment