I have been trying to google this but I still couldn't pinpoint the exact answer to the question in my head.
I have used php artisan
to create a migration file to set up a table called blogs
(note the plural). Previously, the table was called blog
(singular) and the factory would not seed because the error shown on the terminal was that no relations found for "blogs"
- which didn't make sense to me because every reference I used in the controllers, models and factories were singular. It would not let me seed until I have rolled back the migration and re-created the table as blogs
in plural form.
And the strangest thing is that I have kept everything else in singular still, anyone got any clues as to why the seeding works only when I used plural for the table's name?
This is my migration file after the table is revised from blog
to blogs
:
class CreateBlogsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('title', 255);
$table->text('body');
$table->text('user_id');
});
}
This is my factory - named BlogFactory
:
namespace Database\Factories;
use App\Models\Blog;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class BlogFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Blog::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'title' => $this->faker->sentence, //Generates a fake sentence
'body' => $this->faker->paragraph(30), //generates fake 30 paragraphs
'user_id' => User::factory() //Generates a User from factory and extracts id
];
}
}
This is my model - named Blog
:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
use HasFactory;
protected $fillable = [
'title',
'body',
'user_id',
];
}
This is my controller - named BlogController
:
<?php
namespace App\Http\Controllers;
use App\Models\Blog;
use Illuminate\Http\Request;
class BlogController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return Blog::all();
}