How to get table attribute inside laravel model?

Member

by addison , in category: PHP Frameworks , a year ago

How to get table attribute inside laravel model?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 10 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.

Related Threads:

How to get the id of current saved model in laravel?
How to get select field in model using laravel?
How to get object values inside array in laravel?
How to get value from more than two table in laravel?
How to get values from pivot table in laravel?
How to get the next record in a table using laravel?