fefe
fefe

Reputation: 9065

Get MySQL table columns using Eloquent in Laravel

How would I get inside of a custom model the columns for a specific MySQL table using Eloquent in Laravel

I was trying DB::query("SHOW COLUMNS FROM " . $table) but without any success

Upvotes: 6

Views: 6334

Answers (3)

Serhii Korneliuk
Serhii Korneliuk

Reputation: 87

You can get all the columns of your table as a collection where each column is represented as an object. You can even use your model.

Use in You code

$columns = MyModel::describe();

Add a static method to the model

/**
 * Retrieve a collection of sAttributeValue table columns with their corresponding metadata.
 *
 * @return \Illuminate\Support\Collection
 */
public static function describe()
{
    $collection = collect([]);
    $columns = DB::select("SHOW COLUMNS FROM ".DB::getTablePrefix().MyModel::query()->from);
    if ($columns) {
        foreach ($columns as $column) {
            if ($column) {
                $item = new \stdClass();
                foreach ($column as $key => $value) {
                    $item->{strtolower($key)} = $value;
                }
                $collection->put($item->field, $item);
            }
        }
    }
    return $collection;
}

Result

1 Illuminate\Support\Collection {#1295 ▼
  #items: array:7 [▼
    "id" => {#1300 ▼
      +"field": "id"
      +"type": "bigint unsigned"
      +"null": "NO"
      +"key": "PRI"
      +"default": null
      +"extra": "auto_increment"
    }
    "attribute" => {#1294 ▶}
    "position" => {#1304 ▶}
    "alias" => {#1305 ▶}
    "base" => {#1307 ▶}
    "created_at" => {#1308 ▶}
    "updated_at" => {#1309 ▶}
  ]
  #escapeWhenCastingToString: false
}

Upvotes: 1

Andreas
Andreas

Reputation: 8029

There's no Eloquent function for this as it is considered out of its scope. I'd just do the following:

DB::select('show columns from '.(new MyModel)->getTable());

Upvotes: 0

sidneydobber
sidneydobber

Reputation: 2910

What you are using is not Eloquent, but raw database queries.

RAW queries:

$table = 'your_table';
$columns = DB::select("SHOW COLUMNS FROM ". $table);

Upvotes: 6

Related Questions