DEV Community

Cover image for How to Get Table using Model and Table Columns in Laravel?
Code And Deploy
Code And Deploy

Posted on

How to Get Table using Model and Table Columns in Laravel?

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/how-to-get-table-using-model-and-table-columns-in-laravel

In this post, I will show you how to get a table name using the model and the table columns in Laravel 8. If you need to generate the table name using the model and display the table columns, this post is for you.

Currently, I'm doing a task that will get the assigned table in the model and display the table columns.

So here is the code on how to do it. In your controller method add this code.

/**
 * Display a listing of the resource.
 * @return Renderable
 */
public function index()
{   
    $model = '\App\Models\User';

    if(method_exists($model, 'getTable')) {
        // Get table name using model
        $tableName = (new $model)->getTable();
        // Get table columns
        $tableColumns = Schema::getColumnListing($tableName);

        print_r($tableColumns);
    }
}
Enter fullscreen mode Exit fullscreen mode

Result:

Array
(
    [0] => id
    [1] => name
    [2] => first_name
    [3] => last_name
    [4] => email
    [5] => username
    [6] => email_verified_at
    [7] => password
    [23] => created_at
    [24] => updated_at
)
Enter fullscreen mode Exit fullscreen mode

Now you have an idea of how to extract the model table name and get all columns into it.

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/how-to-get-table-using-model-and-table-columns-in-laravel if you want to download this code.

Happy coding :)

Top comments (0)