Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add column aliasing option in Eloquent Model #8200

Closed
wants to merge 4 commits into from
Closed

Add column aliasing option in Eloquent Model #8200

wants to merge 4 commits into from

Conversation

treythomas123
Copy link

This allows developers to use Eloquent model attribute names that differ from the actual names of the columns. This is accomplished by adding an $aliases field to the Model (similar to $appends, visible, hidden, etc.)

For example, if you're dealing with a legacy database you can't change, you can remap some ugly field names to friendlier ones:

protected $aliases = [
    'FIELD_03' => 'email',
    'FIELD_12' => 'name'
];

This allows you to access the fields by the alias name:

User::find($id)->email; // returns the value in database column FIELD_03

It works with query builder too, so this:

User::where('FIELD_12', 'like', 'jobs')
  ->orWhere('FIELD_03','[email protected]')

Becomes:

User::where('name', 'like', 'jobs')
  ->orWhere('email','[email protected]')

@RomainLanz
Copy link

Nice one! 👍

If it's not accepted in the core, you can send a PR on the Eloquence package made by @jarektkaczyk.

@jarektkaczyk
Copy link
Contributor

@RomainLanz Thanks for mentioning. I added the feature already to the Eloquence package with additional functionality - mapping relations and querying relations, not only aliased local columns.

@treythomas123 Good job

@taylorotwell
Copy link
Member

Since this exists in a package, going to leave it there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants