Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Laravel find plural of models?

If I have a Model "Dog", Laravel will link it to the table "Dogs". Always the plural. Now, if I have a Model "Person", it tries to find the table "People" - also the plural. But how does Laravel know the plural when it's more than just adding a "s"? Is there a tabel with all english nouns?

like image 847
almo Avatar asked May 29 '14 21:05

almo


2 Answers

Laravel 4

In the Illuminate\Database\Eloquent\Model.php you'll find something like str_plural($name) and str_plural is a helper function which uses Str::plural method and in this case, this method looks like this:

public static function plural($value, $count = 2)
{
    return Pluralizer::plural($value, $count);
}

So it's obvious that, Str::plural uses class Illuminate\Support\Pluralizer.php and there you'll find how it actually works. Just read the source code. There is a separate word mapping for irregular word forms with others:

// Taken from Illuminate\Support\Pluralizer
public static $irregular = array(
    'child' => 'children',
    'foot' => 'feet',
    'freshman' => 'freshmen',
    'goose' => 'geese',
    'human' => 'humans',
    'man' => 'men',
    'move' => 'moves',
    'person' => 'people',
    'sex' => 'sexes',
    'tooth' => 'teeth',
);
like image 194
The Alpha Avatar answered Nov 20 '22 18:11

The Alpha


Laravel 5 & 6

The Alpha's answer was for Laravel 4.

To give credit where it is due I wanted to update the answer for Laravel 5+.

Pluralizer now extends from doctrine/inflector to avoid re-inventing the wheel. This library contains some basic rules, e.g.

(m|l)ouse         => _ice
(buffal|tomat)o   => _oes
...all else...    => append 's'

Followed by some "uninflected" (i.e. singular and plural are the same)

deer, fish, etc.

And finally the irregular rules, e.g.

man  => men
ox   => oxen

From the documentation:

Doctrine inflector has static methods for inflecting text.

The methods in these classes are from several different sources collected across several different php projects and several different authors. The original author names and emails are not known.

Pluralize & Singularize implementation are borrowed from CakePHP with some modifications.

So it's interesting how much all of the frameworks borrow and reuse from one another.

like image 44
andrewtweber Avatar answered Nov 20 '22 19:11

andrewtweber