Skip to content

Instantly share code, notes, and snippets.

@uoxiu
Created November 4, 2015 07:40
Show Gist options
  • Select an option

  • Save uoxiu/2f5a831617a6f0efec0c to your computer and use it in GitHub Desktop.

Select an option

Save uoxiu/2f5a831617a6f0efec0c to your computer and use it in GitHub Desktop.
<?php
namespace App\Models;
use Illuminate\Support\Facades\DB;
trait EloquentNamesTrait
{
protected static $tableName = null;
public static function name()
{
if (static::$tableName === null) {
return static::$tableName = ((new self)->getTable());
} else {
return static::$tableName;
}
}
public static function field($name)
{
return static::name() . '.' . $name;
}
public static function alias($name, $aliasName)
{
return DB::raw(static::field($name) . ' as ' . $aliasName);
}
public static function getValue($id, $fieldName = 'name')
{
if ($id) {
$entity = self::find($id);
if (isset($entity[$fieldName])) {
return $entity[$fieldName];
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment