skip to Main Content

I’m currently taking Laravel 8 From Scratch by Jeffry Way. I’m currently in episode 54 when I faced the error below after trying to migrate:fresh –seed. I’m pretty sure I followed everything from the start. Can you please help me point out the mistake? thank you

lance@lance-vivobook:~/laravel-blog$ php artisan migrate:fresh

  Dropping all tables ............................................. 38ms DONE

   INFO  Preparing database.  

  Creating migration table ......................................... 8ms DONE

   INFO  Running migrations.  

  2014_10_12_000000_create_users_table ............................ 32ms DONE
  2014_10_12_100000_create_password_reset_tokens_table ............ 19ms DONE
  2019_08_19_000000_create_failed_jobs_table ...................... 17ms DONE
  2019_12_14_000001_create_personal_access_tokens_table ........... 28ms DONE
  2023_07_14_080115_create_posts_table ............................ 40ms FAIL

   IlluminateDatabaseQueryException 

  SQLSTATE[HY000]: General error: 1005 Can't create table `blog`.`posts` (errno: 150 "Foreign key constraint is incorrectly formed") (Connection: mysql, SQL: alter table `posts` add constraint `posts_category_id_foreign` foreign key (`category_id`) references `categories` (`id`) on delete cascade)

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:795
    791▕         // If an exception occurs when attempting to run a query, we'll format the error
    792▕         // message to include the bindings with SQL, which will make this exception a
    793▕         // lot more helpful to the developer instead of just the database's errors.
    794▕         catch (Exception $e) {
  ➜ 795▕             throw new QueryException(
    796▕                 $this->getName(), $query, $this->prepareBindings($bindings), $e
    797▕             );
    798▕         }
    799▕     }

      +9 vendor frames 

  10  database/migrations/2023_07_14_080115_create_posts_table.php:24
      IlluminateSupportFacadesFacade::__callStatic()
      +35 vendor frames 

  46  artisan:37
      IlluminateFoundationConsoleKernel::handle()

create_posts_table.php

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('category_id')->constrained()->cascadeOnDelete();
            $table->string('slug')->unique();
            $table->string('title');
            $table->text('excerpt');
            $table->text('body');
            $table->timestamps();
            $table->timestamp('published_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

PostFactory.php

class PostFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'user_id' => User::factory(),
            'category_id' => Category::factory(),
            'title' => $this->faker->sentence(),
            'slug' => $this->faker->slug(),
            'excerpt' => '<p>'.implode('</p><p>', explode("nn", $this->faker->paragraphs(2, true))).'</p>',
            'body' => '<p>'.implode('</p><p>', explode("nn", $this->faker->paragraphs(6, true))).'</p>',
        ];
    }
}

Post.php

class Post extends Model
{
    use HasFactory;

    protected $guarded = [];
    protected $with = ['category', 'author'];
    // protected $fillable = ['title', 'excerpt', 'body'];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
    public function author()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

create_categories_table

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('slug')->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('categories');
    }
};

CategoryFactory

class CategoryFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'name' => $this->faker->unique()->word(),
            'slug' => $this->faker->unique()->slug()
        ];
    }
}

Category.php

class Category extends Model
{
    use HasFactory;

    public function post()
    {
        return $this->hasMany(Post::class);
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    I should have used php artisan migrate instead of php artisan migrate:fresh --seed. Brombeer was right - Make sure the categories table is being created before it is referenced


  2. Its a problem with

    foreign key (`category_id`) references `categories` (`id`)
    

    it searches for table categorys, but it doesnt exist.

    $table->foreignId('category_id')->constrained()->cascadeOnDelete();
    

    it needs a reference to find correct table.
    https://laravel.com/docs/8.x/migrations#foreign-key-constraints

    $table->foreign('category_id')->references('id')->on('categories');

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search