Laravel get all Column Names from Table Example

Laravel get all column names from the table; In this tutorial, we will show you how to get all columns of a table in the Laravel application. Sometimes we need to get the all column’s names from a table then below are two examples useful for you.

We can get the table name in the controller using the getTable() method and the columns name using the Schema facades or DB Schema builder easily.

Example 1:

First we can use the getSchemaBuilder with getTable() methods;

use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
    public function getTableColumns()
    {
        $user= new User;
        $table = $user->getTable();

        return DB::getSchemaBuilder()->getColumnListing($table);
    }
}

Example 2:

We can use the Schema with the getColumnListing() method;

use Illuminate\Support\Facades\Schema;
class UserController extends Controller
{
    public function getTableColumns()
    {
        $user= new User;
        $table = $user->getTable();

        return Schema::getColumnListing($table);
    }
}

I hope its works for you.

Leave a Comment