Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to get Model name based on table name

Is there any way to get Model name based on table name in Laravel?

For example, I have a User model:

class User extends Model {
    // This class is related to `users` table in Database.
}

Suppose that this Model (User) is related to users table in database. I want a function like this:

getModelName('users'); // This should return 'User'

Is there something like this?

like image 689
Mustafa Ehsan Alokozay Avatar asked Jan 18 '26 03:01

Mustafa Ehsan Alokozay


1 Answers

The Illuminate\Database\Eloquent\Model has a function for returning the table name for the given model. https://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Model.php#L1951

You could reverse engineer this function to something like

function getModelName($table)
{
    return Str::studly(Str::singular($table));
}
like image 181
Wader Avatar answered Jan 19 '26 17:01

Wader



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!