define an alias name for primary key in a model that is extended in laravel

laravel wherehas
laravel hasonethrough
laravel pivot model
laravel eloquent relationships example
laravel nested relationships
laravel create many
laravel model attributes
laravel hasmanythrough pivot

I have a Stuff Model like this :

class Stuff extends Model
{
    protected $primaryKey = 'stuff_id';
    protected $fillable   = ['stuff_id' , 'title' , 'desc'];
    protected $dates = ['deleted_at'];
}

In the other hand there is a Product model that extended from Stuff Model like this :

class Product extends Stuff 
{
    protected $fillable   = ['quantity' , 'picture'];
}

As you can see beacause Product is extended from Stuff and primary key of Stuff is stuff_id , Anywhere that I want to call a Product instances and needs to print it's id should use a $product->stuff_id while I want use a clearer name for that like $product->product_id.

Is there any way that can define a alias primary key in child model that interpreted to stuff_id in back-end when running queries on database.

To turn product_id into an alias of stuff_id:

...
$product->product_id // resolves to $product->stuff_id
...
public function getProductIdAttribute(): int
{
    return $this->stuff_id;
}
...

Eloquent: Relationships - Laravel, Eloquent determines the foreign key of the relationship based on the model name. the foreign key should have a value matching the id (or the custom $​primaryKey ) column of the parent. When defining the RoleUser model, we will extend the Pivot class: use Illuminate\Database\Eloquent\Relations\Relation; $​alias  The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Before getting started, be sure to configure a database connection in config/database.php. To get started, create an Eloquent

Instead of using $primaryKey, you can override the function that reads from that variable.

In your Stuff model, try adding something along the lines of:

/**
 * Get the primary key for the model.
 *
 * @return string
 */
public function getKeyName(): string
{
    return [
        Stuff::class => 'stuff_id',
        Product::class => 'product_id',
    ][get_class($this)];
}

And for reference, the default behavior: (Illuminate/Database/Eloquent/Model.php)

/**
 * Get the primary key for the model.
 *
 * @return string
 */
public function getKeyName()
{
    return $this->primaryKey;
}

Eloquent model alias column, Above example will rename email column of users table to username. Alias Column Syntax Create Laravel Eloquent model without a primary key To create an All Eloquent models extend Illuminate\Database\Eloquent\Model class. The third argument is the name of the foreign key on the intermediate model. The fourth argument is the name of the foreign key on the final model. The fifth argument is the local key, while the sixth argument is the local key of the intermediate model:

Using Global Scope:

//Say ProductScope.php
namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Schema;

class ProductScope implements Scope
{
    protected $model_name;
    public function __construct($model_name)
    {
        $this->model_name = $model_name;
    }

    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $attr = Schema::getColumnListing($this->model_name);

        $attr_ =  array_map(function ($item){
            return $item === 'stuff_id' ? $item.' as product_id' : $item;
        }, $attr);

        $builder->select($attr_);
    }
}

Then in the Product Model:

use App\Scopes\ProductScope;

class Product extends Stuff
{
    protected $table = 'stuffs';
    protected $primaryKey = 'stuff_id';
    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new ProductScope('stuffs'));
    }
}

This will replace the stuff_id with product_id

Set a New Primary key in Model, Is there any way I can adjust the primary key that the model uses? Such as: protected $primaryKey = 'employer_id'; I have a problem where grabbing da This is how Laravel 5.2 gets the primary key and this is how it puts it together with the table name and finally this is how it's used in the find() method. Before renaming a table, you should verify that any foreign key constraints on the table have an explicit name in your migration files instead of letting Laravel assign a convention based name. Otherwise, the foreign key constraint name will refer to the old table name.

Use UUID as primary key of Laravel Eloquent ORM., Traditionally we use an integer value as id of model, but nowadays we use a Usually we use $table->id(); statement to create id column… Use UUID as primary key of Laravel Eloquent ORM. So we need to extend our Person model class. Aliasing 'Person' to 'App\Person' for this Tinker session. For this example, we’ll name the database ‘laravel’ and simply use the MySQL ‘root’ user account. Likewise, I’m assuming that the MySQL ‘root’ account does not have a password. Obviously, this is VERY insecure, but it is fine for your local development environment.

Laravel (5.7) Eloquent Relationships, We define eloquent relationships as methods on our Eloquent model classes. The Eloquent determines the foreign key of the relationship based on the a value matching the id (or the custom $primaryKey) column of the parent. while custom polymorphic many-to-many pivot models should extend the  Route filters provide a convenient way of limiting access to a given route, which is useful for creating areas of your site which require authentication. There are several filters included in the Laravel framework, including an auth filter, an auth.basic filter, a guest filter, and a csrf filter. These are located in the app/filters.php file.

michaelbaril/smoothie: Some fruity additions to Laravel's , To use this method, you need your model to extend the Baril\Smoothie\Model class instead of Illuminate\Database\Eloquent\Model . It allows for explicit ordering of collections by primary key. There are 2 different ways to define aliases:. In model's validate() process, the filters() will be performed before rules(), which means the input data validated by rules() is already be filtered. To enable filters for validate(), you should declare filters for the attributes you plan to perform. This should be done by overriding the filters() method.

Comments
  • or just have a $primaryKey = 'product_id' on the Product model as well?
  • and to post a more defined answer, could you show some example code of how you would envision how you would handle the data if hyphothetically the code behind the scenes already worked?
  • Have you thought about Global scopes? laravel.com/docs/5.4/eloquent#query-scopes
  • @OluwatobiSamuelOmisakin, can you explain more as a answer with example?
  • @A.B.Developer I did using Scope.
  • Note that there is not a product_id field at all. I need an alias only in Product model that when call product_id considered as stuff_id.
  • Ah, in that case check my other answer: