Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







Route Model Binding In Laravel & Change Default Column id To Another Column


MODEL ROUTE MODEL BINDING PHP LARAVEL ROUTING LARAVEL
04th May 2020 3 mins read
Share Article     Share On WhatsApp   Buy Me Coffee | StackCoder Buy Coffee


Hooray! I am up with another article. In this article you will learn What is Route Model Binding in Laravel and how to change the default column from id to another column like unique_id


Prerequisites


Fresh installation of Laravel or working Laravel project.


Note: Here I am taking an example of Blog. But the concept remains same.

What The Heck Is Route Model Binding?


We usually use routes similar to this /posts/{id} where we are passing id which corresponds to posts->id, this is usually called as injecting a model id to route/controller method. Which later you will use to query your database like the following


/** web.php */
Route::get('/posts/{id}', 'PostsController@show');

/** PostsController.php */
public function show($id){
    /** Fetch the post details by $id passed */
    $post = Post::where(['id' => $id])->first();
    
    if(!$post){
        abort(404, 'Post Not Found');
    }
    
    return view('posts.show', [
        'post' => $post
    ]);
}


What if the querying part is handled by Laravel. Wouldn't that be easier on your life. Yes, this is what we call Route Model Binding. Laravel automatically injects the model instances in your routes.


In the following example instead of post id, we are injecting entire post model instance which matches it.


Laravel handles the id with route model binding and given us the result . Now the code is very clean and consise.


To explain in simple words Laravel with fetch the record from database by comparing id column


/** web.php */
/** Dont worry on the {post} naming, usually you may take {id} too :) */
Route::get('/posts/{post}', 'PostsController@show');

/** PostsController */

/** Your show() methos will look like the following */
public function show(Post $post){
    /** If $post value passed is not found then laravel will call abort() automatically */
    return view('posts.show', [
        'post' => $post
    ]);
}

Change Route Model Binding Column id -> unique_id


By default route model binding binds to your primary key column ie id but what if you need to change the column to other column.


Laravel has given an option to override column id with other column in your models. For example in my Post model I can change the id with unique_id in the following way


/** Other Code */
class Post extends Model{
  /** Other Code */

  public function getRouteKeyName(){
    return 'unique_id';
  }

  /** Other Code */
}


You can override within the function getRouteKeyName(). Here I wanted unique_id to be queried all the time for route model binding for Post model.


Conclusion


Hope this article was helpful. If you have liked the article then don't forget to share my website with your friends.


WHATS NEXT?


You might be interested in reading few of my other articles


How To Run Raw Queries Securely In Laravel

Laravel 7.x Multiple Database Connections, Migrations, Relationships & Querying

How To Install Apache Web Server On Ubuntu 20.04 / Linux & Manage It

How To Create / Save / Download PDF From Blade Template In PHP Laravel

How To Add Free SSL Certificate In cPanel With ZeroSSL & Certbot

How To Securely SSH Your Server & Push Files With FileZilla

How To Push Files To CPanel / Remote Server using FTP Software FileZilla

How To Install Linux, Apache, MYSQL, PHP (LAMP Stack) on Ubuntu

How To Cache Static Files With NGINX Server

Redirect www to a non-www website or vice versa

How To Create Free SSL Certificate With Lets Encrypt/Certbot In Linux (Single / Multiple Domains)

How To Install Linux, NGINX, MYSQL, PHP (LEMP Stack) on Ubuntu

PHP Built-In Web Server & Testing Your Development Project In Mobile Without Any Software

How To Do Google reCAPTCHA Integration In PHP Laravel Forms


Happy Coding :)








Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing