Demystifying Route Model Binding in Laravel

Route Model Binding
//routes/web.php
Route::get('/post/{post}', 'PostsController@show');
//PostsController.php
public function show(Post $post) {
return view('posts.show', [
'post' => $post
]);
}
public function show($id) {    $post = Post::find($id);
if( !$post) {
abort(404);
}
return view('posts.show', [
'post' => $post
]);
}
if (! $parameterName = 
static::getParameterName($parameter->name, $parameters)) {
continue;
}
$instance = $container->make($parameter->getClass()->name);
$model = $instance->resolveRouteBinding($parameterValue, $route->bindingFieldFor($parameterName);
public function resolveRouteBinding($value, $field = null)
{
return $this->where($field ?? $this->getRouteKeyName(), $value)->first();
}
throw (new ModelNotFoundException)->setModel(get_class($instance), [$parameterValue]);
$route->setParameter($parameterName, $model);
Route::get('/post/{post:slug}', 'PostsController@show');
public function show(Post $post) {
if( $post->status != 1) {
abort(404);
}
return view('posts.show', [
'post' => $post
]);
}
Route::bind('activePost', function ($slug) {
return \App\Post::where('slug', $slug)
->where('status', 1)->firstOrFail();
});
Route::get('/post/{activePost:slug}', 'PostsController@show');

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store