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);
  1. We could define a method in our Model name as getRouteKeyName(). This would return the column which Laravel will use to fetch the data from DB. By default this method returns the primaryKey and hence Laravel fetches on the basis of id.
  2. We could also tell Laravel to explicitly look for a column rather than depending upon the value of getRouteKeyName(). We could do so by changing our Route as below:
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');

--

--

--

Freelancer Developer.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Weekly Development Update

Everything Is a Program — Chapter 1 — Machines

OpenShift v3.9 on Linode with Hostname

Loan Approval Prediction application

Day 24–101 Days of DevOps -Jenkins Pipeline(Scripted vs Declarative)

Get file metadata from PowerShell script

Flutter in Mobile App Development — Pros & Risks for App Owners

(PDF) The Little Schemer — 4th Edition

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
Saurabh Mahajan

Saurabh Mahajan

Freelancer Developer.

More from Medium

Laravel multithreading simulation package

How to write raw sql query migration in laravel ?

How To Generate QR code in laravel 8 — Phpflow.com

Laravel 8 Group By Query Example