Last active
May 14, 2024 02:19
-
-
Save stevebauman/3d40e1760981ec01a3a70bdc0969aae8 to your computer and use it in GitHub Desktop.
Throw exception on Eloquent model binding name mismatch
This file contains hidden or 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
https://goggle.com/