Skip to content

Adding the first models

Clio Brichaut edited this page Jan 14, 2023 · 1 revision

To create the first two models, Products and Baskets:

  1. Run ./vendor/bin/sail artisan make:model Product --all and ./vendor/bin/sail artisan make:model Basket --all to generate the models, factories, etc.

  2. Configure the Product properties (= name, price) by editing /app/database/migrations/xxxx_xx_xx_xxxxxx_create_products_table.php:

public function up()
{
	Schema::create('products', function (Blueprint $table)
	{
		$table->id();
		$table->string('name');
		$table->float('price');
		$table->timestamps();
	});
}
  1. Create the intermediate table with ./vendor/bin/sail artisan make:migration create_basket_product_table and configure the foreign keys in the generated migration /app/database/migrations/xxxx_xx_xx_xxxxxx_create_basket_product_table.php:
public function up()
{
	Schema::create('basket_product', function (Blueprint $table)
	{
		$table->foreignId('basket_id')->constrained();
		$table->foreignId('product_id')->constrained();
		$table->dateTime('removal_date')->nullable();
		$table->timestamps();
	});
}

public function down()
{
	Schema::table('basket_product', function (Blueprint $table)
	{
		$table->dropForeign(['basket_id']);
		$table->dropForeign(['product_id']);
	});

	Schema::dropIfExists('basket_product');
}
  1. Set the ManyToMany relationship in the Models /app/app/Models/Product.php and /app/app/Models/Basket.php:
// class Product

/**
 * @return BelongsToMany<Basket>
 */
public function baskets(): BelongsToMany
{
	return $this->belongsToMany(Basket::class)->withTimestamps()->withPivot('removal_date');
}

// class Basket

/**
 * @return BelongsToMany<Product>
 */
public function products(): BelongsToMany
{
	return $this->belongsToMany(Product::class)->withTimestamps()->withPivot('removal_date');
}
  1. Execute the migrations with ./vendor/bin/sail artisan migrate.

  2. Open http://localhost:8080 to see the database with all its tables (including Laravel's default users, migrations, etc.).

Clone this wiki locally