Table of contents

get model table name in laravel

In this short post, I will show you how to get the model table name in Laravel. In my previous tasks, I generated all the models and display all tables from the models I generated. If you have the same task maybe it can help you.

 

In this example, we will use the User.php model and get the table name. To do it just see my code below:

 

Our Controller

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function index() 
    {
        $model = new User;
        $table = $model->getTable();
        print_r($table);
    }
}

 

As you can see with the user of $model->getTable(); method we get the model table name.

 

Our Route

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::group(['namespace' => 'App\Http\Controllers'], function()
{   

    Route::get('/users', 'UsersController@index');

});

 

Read Also: How to Get Table using Model and Table Columns in Laravel?

 

That's it I hope it helps.