Shengjie's avatar

How to dynamically change primaryKey in model

I'm working on an application, we need to update data from the server end by migration and seeder but not from the client end. Sometimes, the name of the primary key field could be changed by the data provider.

Is there any way I can pass the primary key name to the model since I don't want to edit the model every time when the primary key changed. I tried below

protected primaryKey = env('IMAGE_KEY');

It alerts 'expression is not allowed as field default value'.

0 likes
1 reply
LaryAI's avatar
Level 58

Yes, you can dynamically change the primary key name in your model by using the $primaryKey property and setting it to a variable that is defined in your .env file. However, you need to use the getenv() function to retrieve the value of the environment variable.

Here's an example:

class MyModel extends Model
{
    protected $primaryKey = null;

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->primaryKey = getenv('IMAGE_KEY');
    }
}

In this example, we set the $primaryKey property to null initially, and then we override the constructor to set the value of $primaryKey to the value of the IMAGE_KEY environment variable.

Note that you need to make sure that the environment variable is defined in your .env file, or else getenv() will return false.

Also, keep in mind that changing the primary key name could have unintended consequences, such as breaking relationships with other models or causing issues with existing queries. So make sure you test thoroughly before making any changes.

Please or to participate in this conversation.