Search code examples
phplaraveldatabase-migration

Access laravel migration and return the return the Blueprint table object


I wonder if there is a way that I can access the Blueprint in migration file and return it in a external file. Example, I have the following USERS migration:

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

So I wonder if I could "access" this object to use it in a external file. Imagine I have a file get_data_from_migration.blade.php and I could do something like:

use Illuminate\Database\Migrations\Migration;

$table = Migration('migrationName');
var_dump($table);

So it would print the user table Blueprint on the screen. I know it would not be the correct sintax but I use it only to ilustrate the idea.

Anyway, what I need is to print on the screen something like:

You colums in the table are:

  • id
  • name
  • email
  • email_verified_at
  • password

Thank you


Solution

  • You could try something like this:

    use Illuminate\Support\Facades\Schema;
    
    // for your User model
    $table = $user->getTable();
    $columns = Schema::getColumnListing($table);
    

    Or if you don't have an instance of User you could try:

    use Illuminate\Support\Facades\Schema;
    
    $table = with(new User)->getTable();
    $columns = Schema::getColumnListing($table);
    

    Or if you just want it for the one model you could just hard code the table name.

    use Illuminate\Support\Facades\Schema;
    
    $columns = Schema::getColumnListing('users');