Alexandre Demelas
Alexandre Demelas

Reputation: 4710

Laravel: How to aliases a column name

Imagine that exists a User model instance with below properties:

User {
  id: 1,
  name: 'Alexandre',
  email: 'alexandre@email.com'
}

And in the view I want to automatically print each column alias + value by using a @foreach statement, for example:

<ul>
    @foreach($user as $attribute)
        <li>{{ $attribute->column_alias }}: {{ $attribute->value }}</li>
    @endforeach
</ul>

Would work like the Validator attributes aliasing. The output result should be:

There is some way to do this?

Upvotes: 1

Views: 1387

Answers (2)

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

Try this.

In your model add this

/**
 * @var array
 */
protected $alias = [
    'name' => 'user name',
    'email' => 'User email',
    'other property' => ' property alias'
];

/**
 * @param $attribute
 * @return string
 */
public function getAttributeAlias($attribute) {
    return $this->alias[$attribute] ?: '';
}

then you can use

<ul>
    @foreach($user->getAttributes() as $attribute => $value)
        <li>{{ $user->getAttributeAlias($attribute) }}: {{ $value }}</li>
    @endforeach
</ul>

For make it out of model you can add config file like this alias.config

return [
    'user' => [
        'name' => 'User name',
        'email' => 'User Email',
        'other property' => 'property alias'
    ],
    'other model' => [
         'other property' => 'property alias'
    ]
];

Usage

<li>{{ config('alias.user.' . $attribute, '')) }}: {{ $value }}

Upvotes: 2

Joel Hinz
Joel Hinz

Reputation: 25414

You can call $someModel->toArray() (or ->getAttributes(), which will hide sensitive data such as passwords) to get the underlying data array. That way, you can print the column names and their values:

<ul>
    @foreach($user->toArray() as $key => $attribute)
        <li>{{ $key }}: {{ $attribute }}</li>
    @endforeach
</ul>

But your keys will say e.g. "id", "name", etc., and not a longer word. I would suggest putting that in a translation file. Just as an example:

<ul>
    @foreach($user->toArray() as $key => $attribute)
        <li>{{ __('user-model-keys.'.$key) }}: {{ $attribute }}</li>
    @endforeach
</ul>

resources/lang contains a folder for every language you want your application in. Every file in there contains your translations as a returned array. So if you want to translate "id" as "Identification", and your language is English, then given the above code you create a file resources/lang/en/user-model-keys.php and put this inside:

<?php
return [
    'id' => 'Identification'
];

Now, __('user-model-keys.id') will translate "id" to "Identification".

You can read more about localisation here: https://laravel.com/docs/5.6/localization

Upvotes: 3

Related Questions