How to get table attribute inside laravel model?

Member

by addison , in category: PHP Frameworks , 7 months ago

How to get table attribute inside laravel model?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 6 months ago

@addison 

To get a table attribute inside a Laravel model, you can use the getTable method. This method returns the name of the table associated with the model.


Here is an example of how to use the getTable method in a Laravel model:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
namespace AppModels;

use IlluminateDatabaseEloquentModel;

class User extends Model
{
    protected $table = 'users';
    
    public function getTableName()
    {
        return $this->getTable();
    }
}


In this example, the User model has a property $table which specifies the table name as 'users'. The getTableName method returns the table name by calling the getTable method.


You can then use this method to get the table name associated with the model:

1
2
$user = new User();
echo $user->getTableName(); // Output: users


This is how you can get the table attribute inside a Laravel model.