https://laravel.com/docs/11.x/eloquent-relationships
Pivot tables;
https://laraveldaily.com/post/pivot-tables-and-many-to-many-relationships
hasMany: When one thing has multiple of another, e.g. a recipe has several ingredients (and each ingredient with quantity etc. belongs to one recipe only);
In this case, you can add a mix_id on every ingredient, then connect them with a hasMany on your mix model, and you dont need an extra table!
belongsToMany: When relationships work in two ways (e.g. users can favorite recipes, and all recipes can be favorited by multiple users)
In this last case, you need a pivot table with id, user_id, and mix_id
Create pivot table: ‘1.) Create a new migration, using singular table names in alphabetical order (default):’
php artisan make:migration create_alpha_beta_table
Then in the migration:
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('mix_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('mix_id')->references('id')->on('mixes')->onDelete('cascade');
See if item has related items: Has many (e.g. a blog post with many comments):
Eloquent: Relationships - Laravel 11.x - The PHP Framework For Web Artisans
In
<?php
namespace App\\Models;
use Illuminate\\Database\\Eloquent\\Model;
use Illuminate\\Database\\Eloquent\\Relations\\HasMany;
class Post extends Model{
public function comments(): HasMany{
return $this->hasMany(Comment::class);
}
}