php artisan make:model -m Categorie
public function up(): void
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
php artisan make:migration create_pivot_post_categorie
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();
});
}
php artisan migrate
class Post extends Model
{
use HasFactory;
public function categories()
{
return $this->belongsToMany(Categorie::class);
}
}
@foreach ($posts->categories as $categorie)
{{ $categorie->name }},
@endforeach