How to get column names from table in Laravel

Updated at 10-Jan-2022, By samar

How to get column names from table in Laravel

We’ll attempt to use programming in this lesson to solve the "How to get column names from table in Laravel" puzzle.

You can get all the column names from a table using the DB facade and Schema facade. You have to call the getColumnListing() method (using DB and Schema facade) by passing the table name as an argument to get all columns from the table.
  • Laravel get column names from a table

    --PATH routes\web.php
    Route::get('/get-table-columns', function(){
        $table = 'users';
        return DB::getSchemaBuilder()->getColumnListing($table);
    });
    
    //Output:
    //["id","name","email","email_verified_at","password","remember_token","created_at","updated_at"]
    
    //Methods you can use to get the list of columns from a table.
    Schema::getColumnListing($table);
    //Or
    DB::getSchemaBuilder()->getColumnListing($table);
    
    //You can easily use facade (Schema and DB facade) using use statement. 
    use Illuminate\Support\Facades\Schema;
    use Illuminate\Support\Facades\DB;
    

    You have to copy/paste code in routes\web.php and visit URL http://localhost:8000/get-table-columns to get all column (field) names of a specified table.

Back to code snippet queries related laravel