Para crear un sistema de blog simple en Laravel con tablas relacionadas para categorías, etiquetas, publicaciones y una tabla pivote para las etiquetas de las publicaciones, sigue los pasos a continuación. Vamos a definir las migraciones y los modelos necesarios para estas tablas y sus relaciones.
Paso 1: Crear las Migraciones
Primero, crea las migraciones para las tablas.
php artisan make:migration create_categories_table php artisan make:migration create_tags_table php artisan make:migration create_posts_table php artisan make:migration create_post_tag_table
Luego, edita las migraciones para definir la estructura de las tablas.
Migraciones Actualizadas
create_categories_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('svg');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('categories');
}
}
create_tags_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTagsTable extends Migration
{
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('svg');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('tags');
}
}
create_posts_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->foreignId('category_id')->constrained()->onDelete('cascade');
$table->string('excerpt', 500);
$table->text('content');
$table->string('img')->nullable();
$table->string('url')->nullable();
$table->string('ins')->nullable();
$table->string('face')->nullable();
$table->string('youtube')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('posts');
}
}
create_post_tag_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostTagTable extends Migration
{
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->onDelete('cascade');
$table->foreignId('tag_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('post_tag');
}
}Modelos con Relaciones
Vamos a actualizar los modelos para reflejar las relaciones entre estas tablas.
Category.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $fillable = ['name', 'svg'];
public function posts()
{
return $this->hasMany(Post::class);
}
}
Tag.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
use HasFactory;
protected $fillable = ['name', 'svg'];
public function posts()
{
return $this->belongsToMany(Post::class, 'post_tag');
}
}
Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title', 'category_id', 'excerpt', 'content', 'img', 'url', 'ins', 'face', 'youtube'
];
public function category()
{
return $this->belongsTo(Category::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tag');
}
}Ejecutar las Migraciones
Ejecuta las migraciones para crear las tablas en la base de datos.
php artisan migrate
Opcional: Seeder para Poblar Datos
Para poblar las tablas con datos de prueba, puedes crear seeders. Aquí tienes un ejemplo para DatabaseSeeder.php:
DatabaseSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Category;
use App\Models\Tag;
use App\Models\Post;
class DatabaseSeeder extends Seeder
{
public function run()
{
$categories = Category::factory(5)->create();
$tags = Tag::factory(10)->create();
Post::factory(20)->create()->each(function ($post) use ($tags) {
$post->tags()->attach($tags->random(3));
});
}
}
Factory para Category, Tag y Post
Crea factories para generar datos de prueba:
php artisan make:factory CategoryFactory php artisan make:factory TagFactory php artisan make:factory PostFactory
Luego, define los factories.
CategoryFactory.php
<?php
namespace Database\Factories;
use App\Models\Category;
use Illuminate\Database\Eloquent\Factories\Factory;
class CategoryFactory extends Factory
{
protected $model = Category::class;
public function definition()
{
return [
'name' => $this->faker->word,
'svg' => '<svg></svg>',
];
}
}
TagFactory.php
<?php
namespace Database\Factories;
use App\Models\Tag;
use Illuminate\Database\Eloquent\Factories\Factory;
class TagFactory extends Factory
{
protected $model = Tag::class;
public function definition()
{
return [
'name' => $this->faker->word,
'svg' => '<svg></svg>',
];
}
}
PostFactory.php
<?php
namespace Database\Factories;
use App\Models\Post;
use App\Models\Category;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
protected $model = Post::class;
public function definition()
{
return [
'title' => $this->faker->sentence,
'category_id' => Category::factory(),
'excerpt' => $this->faker->text(200),
'content' => $this->faker->paragraphs(3, true),
'img' => $this->faker->imageUrl(),
'url' => $this->faker->url,
'ins' => $this->faker->url,
'face' => $this->faker->url,
'youtube' => $this->faker->url,
];
}
}Ejecutar los Seeders
Ejecuta los seeders para poblar la base de datos.
php artisan db:seed
Con estos pasos, has configurado un sistema de blog básico en Laravel con categorías, etiquetas, publicaciones y una tabla pivote para las etiquetas de las publicaciones. Ahora puedes explorar y aprender cómo funcionan las relaciones en Laravel. ¡Diviértete aprendiendo!