6

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

2
  • Do you get an error or an unexpected result? Commented May 4, 2014 at 19:16
  • does not return any result Commented May 4, 2014 at 19:34

3 Answers 3

6

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

RAW queries:

$table = 'your_table';
$columns = DB::select("SHOW COLUMNS FROM ". $table);
Sign up to request clarification or add additional context in comments.

6 Comments

thanks for the update but unfortunately I do not get any expected I use it like MyModel::select("SHOW COLUMNS FROM ". $table);
OK, that is Eloquent! The answer works for me, but it might not work with Eloquent.
how do I refactor the method to use in this case raw query
Doesn't seem to work for Eloquent. This is for RAW queries. DB:: is RAW queries.
okay thanks again to use RAW queries is needed to use Illuminate\Support\Facades\DB as DB; in model
|
1

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
}

Comments

0

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());

1 Comment

So it means that I can not handle dynamic tables?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.