Création de la table¶
php artisan make:model -m Categorie
Configuration de cette table¶
public function up(): void
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
Création de la table pivot¶
php artisan make:migration create_pivot_post_categorie
Configuration de la table¶
public function up(): void
{
Schema::create('categorie_post', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->cascadeOnDelete();
$table->foreignId('categorie_id')->constrained()->cascadeOnDelete();
$table->timestamps();
});
}
Lancer les migrations¶
php artisan migrate
Configuration du modèle Post¶
class Post extends Model
{
use HasFactory;
public function categories()
{
return $this->belongsToMany(Categorie::class);
}
}
Affichage dans la Vue¶
@foreach ($posts->categories as $categorie)
{{ $categorie->name }},
@endforeach