'Why do table names have to be plural in Laravel?

I noticed that whenever I create a class using database information in Laravel, the table name must be plural. Why is this?



Solution 1:[1]

They don't have to be plural. To make things easy, by default, Eloquent assumes that, if you have a model User, your database table for it will be users. However, if you want to have another name for your table, you can specify custom tables for your models, by defining a table property. For ex:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'user';

    ...
}

This will tell Eloquent to use the table user on your database when working with the model User.

Solution 2:[2]

Just to add to the accepted answer and to one of its comment. You can make your own Model class that all your other models will use instead of the Laravel one where you can set the naming to singular.

For instance, mine looks like this:

<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class BaseModel extends Model
{
    /**
     * Get the table associated with the model.
     *
     * @return string
     */
    public function getTable()
    {
        return $this->table ?? Str::snake(class_basename($this));
    }
}

And all the other models just extends BaseModel instead of Model and use singular by default for table names.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 matronator