How to get name of primary key from model in laravel?
like this
dd(User::primaryKeyName()); // -> 'user_id'
I want to sort data on primary if 'order' is empty
$data = User::orderBy(Input::get('order', User::primaryKey()), 'ASC')->get();
but have
Non-static method Illuminate\Database\Eloquent\Model::getKeyName() should not be called statically, assuming $this from incompatible context
By default, eloquent assume that each model has a primary key column named id. But if you need to change the primary key with your own custom column name you can change it using the protected $primaryKey a property on your model. Additionally, Eloquent assumes that the primary key is an auto-increment integer.
For defining the primary key, it provides HasKey() method. The Fluent API takes priority over the Data Annotation attributes. To specify the mappings using Code First Fluent API, we have to override the OnModelCreating() method. The OnModelCreating() method is called before the models are created.
Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.
The fastest way to do this is probably like so:
(new User)->getKeyName();
(new User)->getTable();
However, I think the two approaches below provide a cleaner interface to the method.
The first approach uses a static method on your base model class:
class BaseModel extends Model
{
protected static function KeyName() {
return (new static)->getKeyName();
}
protected static function TableName() {
return (new static)->getTable();
}
}
Then inherit from this class in your model:
class ModelName extends BaseModel
{
...
}
And use like this: ModelName::KeyName();
If you don't have access to a base model class you can also use a trait:
trait EloquentGetTableNameTrait
{
public static function TableName()
{
return (new static)->getTable();
}
}
Which you use like this in your model:
class ModelName
{
use EloquentGetTableNameTrait;
...
}
Unfortunately, all these approaches require instantiating an instance of the model, but there is currently no other way to retrieve this value.
Reference: https://github.com/laravel/framework/issues/1436
That method tries to get the value from a protected class property return $this->primaryKey;
and $this
needs a context from a class instance. If you really need to get that name dynamically, you could do this:
App::make('User')->getKeyName();
So your code would look something like this:
$data = User::orderBy(Input::get('order', App::make('User')->getKeyName()), 'ASC')->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With