Change Primary Key field attribute of Laravel Model

Posted on

Usually, in web application development based on Laravel framework, a model created in a file form can be associated with a table exist in a database for further binding. So, a controller represented in another file which is used to define the controller class can directly use that model for further action to operate, to query or to access the table associated with it.

An article which is made to show how to create a model in Laravel framework based on PHP programming language exist with a title named ‘Create Model in Laravel using command’ which can be visited in the following link.

After creating the intended model to be used in a controller file for instance to insert a new record based on the model itself. Usually it will try to search a field named id which is marked as a primary key field. But what if that field itself is not exist so the process of inserting new record to the table based on the model is actually failed ?.

namespace App;

use App\Database;
use App\Employee;
use App\Server;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    //
    protected $table = "mytable";
    protected $primaryKey = "id_db";

}

The above script is a script which is represented a model in form of a file named ‘MyModel.php’. The class name is also MyModel and it must be declared by extending a class named ‘Model’ which is shown in the line follow :

class MyModel extends Model

The other important part which is also a deciding factor to map the model into the corresponding table, it must be declared by adding the following line as shown in the above script :

protected $table = "mytable";

So, based on the title of this article, how is exactly defining a primary key field which has a different field name than ‘id’?. The answer is quite simple, just try to define the new or the actual primary key field name within the class as shown below :

protected $primaryKey = "id_mytable";

On the above line, it means that there is a field for primary key named ‘id_mytable’ exist in the table named ‘mytable’.

One thought on “Change Primary Key field attribute of Laravel Model

Leave a Reply