I'm learning back-end development with Laravel's Lumen framework, and I am writing database seeding class following Laravel's documentation. Below are the codes:
Model app\Photo.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
protected $fillable = [
'link', 'category_id', 'date'
];
}
Model factory database\factories\ModelFactory.php
$factory->define(App\Photo::class, function (Faker\Generator $faker) {
return [
'link' => 'https://placehold.it/' . mt_rand(200, 400),
'category_id' => rand(1, 6),
'date' => date("Y-m-d", mt_rand(1263618000, 1481428800))
];
});
DatabaseSeeder
and PhotoTableSeeder
classes database\seeds\DatabaseSeeder.php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call('PhotoTableSeeder');
}
}
class PhotoTableSeeder extends Seeder
{
public function run()
{
factory(App\Photo::class, 10)->create();
}
}
Previously the table name in MySQL database was photos
and the seeding works perfectly using the command php artisan db:seed
:
Seeded: PhotoTableSeeder
But when I changed the table name to photo
and run the same command, these errors occured:
[Illuminate\Database\QueryException] SQLSTATE[42S02]: Base table or view not found: 1146 Table 'homestead.photos' doesn't exist (SQL: insert into `photos` (`link`, `category_id`, `date`) values (https://placehold.it/259, 3, 2012-05-28))
[PDOException] SQLSTATE[42S02]: Base table or view not found: 1146 Table 'homestead.photos' doesn't exist
I don't know why the old table name is still called. I guess it was saved somewhere or am I missing something, I can't figure out the cause of the error.
Eloquent looks for the Plural form of the Model Class Name as the table in the database. So in this case it was expecting to find a table called "Photos"
if for some reason you need to name the table Photo you can always override the default by adding
to your photo model class. I tend to do this even when I am using the default conventions just as a note to myself exactly which table a model is referencing