Laravel Changing Table’s Primary key

This issue will happen when users use query like the following:

$user = DB::table(‘users’)->find($user_id);

The find() method will assume the primary key configured in Laravel, which will be $id. In order to override this, you need to declare   the MODEL (in this case, model USER) of which you will override the protected $primaryKey value to something else – for example ‘user_id’.

When used in the query builder (DB::table()...) the find() method has the primary key column hardcoded as id:

public function find($id, $columns = array('*'))
    return $this->where('id', '=', $id)->first($columns);

What you should do instead is use where() and first():

$bottle = DB::table('bottle')->where('bottle_ID', 1)->first();

Or if you decide to use Eloquent Models you can specify the key column name:

class Bottle extends Eloquent {
    protected $primaryKey = 'bottle_ID';

And retrieve the model like this:

$bottle = Bottle::find(1);


Leave a Reply

Your email address will not be published. Required fields are marked *