مقالات علاء عامر

نقدم مجموعة شاملة من مقالات التعليمية الهامة في تطوير الويب لتحويل أفكارك إلى واقع رقمي

Database Migrations في Laravel: إدارة قواعد البيانات بكفاءة

Laravel 2026-01-01 علاء عامر

Database Migrations في Laravel: إدارة قواعد البيانات بكفاءة

دليل تخصصي من علاء عامر – مطور ومصمم مواقع وتطبيقات محترف

Database Migrations في Laravel هي نظام التحكم في الإصدار لقاعدة البيانات، تسمح بتتبع وإدارة تغييرات هيكل قاعدة البيانات بطريقة منظمة وآمنة.

2️⃣ بناء المخططات (Schema Building)

Migration أساسي لإنشاء جدول:

<?php
// database/migrations/2023_10_07_000001_create_posts_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            // Primary Key
            $table->id();

            // Basic Fields
            $table->string('title', 255);
            $table->string('slug')->unique();
            $table->text('excerpt')->nullable();
            $table->longText('content');
            $table->string('featured_image')->nullable();

            // Status and Visibility
            $table->enum('status', ['draft', 'published', 'archived'])
                  ->default('draft');
            $table->boolean('is_featured')->default(false);
            $table->boolean('comments_enabled')->default(true);

            // SEO Fields
            $table->string('meta_title')->nullable();
            $table->text('meta_description')->nullable();
            $table->json('meta_keywords')->nullable();

            // Statistics
            $table->unsignedBigInteger('views_count')->default(0);
            $table->unsignedBigInteger('likes_count')->default(0);
            $table->unsignedBigInteger('shares_count')->default(0);

            // Foreign Keys
            $table->foreignId('user_id')
                  ->constrained()
                  ->onDelete('cascade');
            $table->foreignId('category_id')
                  ->constrained()
                  ->onDelete('cascade');

            // Timestamps
            $table->timestamp('published_at')->nullable();
            $table->timestamps();
            $table->softDeletes();

            // Indexes for Performance
            $table->index(['status', 'published_at']);
            $table->index(['user_id', 'status']);
            $table->index('created_at');
            $table->fullText(['title', 'content']); // For search
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

Migration متقدم للجداول المعقدة:

<?php
// database/migrations/2023_10_07_000002_create_categories_table.php
return new class extends Migration
{
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name', 100);
            $table->string('slug')->unique();
            $table->text('description')->nullable();
            $table->string('color', 7)->default('#3B82F6'); // Hex color
            $table->string('icon')->nullable();

            // Hierarchical Structure (Self-referencing)
            $table->foreignId('parent_id')
                  ->nullable()
                  ->constrained('categories')
                  ->onDelete('cascade');

            // Display Order
            $table->unsignedInteger('sort_order')->default(0);
            $table->boolean('is_active')->default(true);

            // SEO
            $table->string('meta_title')->nullable();
            $table->text('meta_description')->nullable();

            // Statistics
            $table->unsignedBigInteger('posts_count')->default(0);

            $table->timestamps();

            // Indexes
            $table->index(['parent_id', 'sort_order']);
            $table->index('is_active');
        });
    }

    public function down()
    {
        Schema::dropIfExists('categories');
    }
};

Migration للجداول المحورية (Pivot Tables):

<?php
// database/migrations/2023_10_07_000003_create_post_tag_table.php
return new class extends Migration
{
    public function up()
    {
        Schema::create('post_tag', function (Blueprint $table) {
            $table->id();

            // Foreign Keys
            $table->foreignId('post_id')
                  ->constrained()
                  ->onDelete('cascade');
            $table->foreignId('tag_id')
                  ->constrained()
                  ->onDelete('cascade');

            // Additional Pivot Data
            $table->timestamp('assigned_at')->useCurrent();
            $table->foreignId('assigned_by')
                  ->nullable()
                  ->constrained('users')
                  ->onDelete('set null');

            // Prevent Duplicate Relationships
            $table->unique(['post_id', 'tag_id']);

            // Indexes for Performance
            $table->index('post_id');
            $table->index('tag_id');

            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('post_tag');
    }
};

4️⃣ إدارة Migrations

تشغيل وإدارة Migrations:

# تشغيل جميع migrations المعلقة
php artisan migrate

# تشغيل migrations مع عرض SQL statements
php artisan migrate --pretend

# تشغيل migrations في بيئة الإنتاج (يتطلب تأكيد)
php artisan migrate --force

# عرض حالة migrations
php artisan migrate:status

# التراجع عن آخر batch من migrations
php artisan migrate:rollback

# التراجع عن عدد معين من batches
php artisan migrate:rollback --step=3

# إعادة تشغيل جميع migrations (خطر!)
php artisan migrate:fresh

# إعادة تشغيل migrations مع تشغيل seeders
php artisan migrate:fresh --seed

# إعادة تشغيل آخر batch
php artisan migrate:refresh

# إعادة تشغيل عدد معين من batches
php artisan migrate:refresh --step=2

إنشاء Migration معقد للإحصائيات:

<?php
// database/migrations/2023_10_07_200001_create_analytics_tables.php
return new class extends Migration
{
    public function up()
    {
        // جدول تتبع الزيارات
        Schema::create('page_views', function (Blueprint $table) {
            $table->id();
            $table->morphs('viewable'); // polymorphic relation
            $table->string('ip_address', 45); // IPv6 support
            $table->string('user_agent')->nullable();
            $table->string('referrer')->nullable();
            $table->string('country', 2)->nullable();
            $table->string('city')->nullable();
            $table->json('device_info')->nullable();
            $table->foreignId('user_id')->nullable()->constrained()->onDelete('set null');
            $table->timestamp('viewed_at')->useCurrent();

            // Indexes for analytics queries
            $table->index(['viewable_type', 'viewable_id', 'viewed_at']);
            $table->index(['ip_address', 'viewed_at']);
            $table->index('user_id');
        });

        // جدول الأحداث المخصصة
        Schema::create('custom_events', function (Blueprint $table) {
            $table->id();
            $table->string('event_name');
            $table->json('event_data')->nullable();
            $table->string('session_id')->nullable();
            $table->foreignId('user_id')->nullable()->constrained()->onDelete('set null');
            $table->timestamp('occurred_at')->useCurrent();

            $table->index(['event_name', 'occurred_at']);
            $table->index('session_id');
        });

        // جدول إحصائيات يومية مجمعة
        Schema::create('daily_stats', function (Blueprint $table) {
            $table->id();
            $table->date('date')->unique();
            $table->json('stats_data'); // تخزين إحصائيات متنوعة
            $table->timestamps();

            $table->index('date');
        });
    }

    public function down()
    {
        Schema::dropIfExists('daily_stats');
        Schema::dropIfExists('custom_events');
        Schema::dropIfExists('page_views');
    }
};

💡 نصائح متقدمة لـ Migrations

  1. استخدم أسماء واضحة للـ migrations تصف الغرض بدقة
  2. اكتب down() methods دائماً للتراجع الآمن
  3. اختبر migrations على بيانات حقيقية قبل الإنتاج
  4. استخدم transactions للعمليات المعقدة
  5. أنشئ نسخ احتياطية قبل تشغيل migrations مهمة
  6. راقب الأداء عند إنشاء فهارس على جداول كبيرة
  7. استخدم Schema::hasTable() للتحقق من وجود الجداول

الخطوة التالية

تعلم Eloquent Relationships و Query Builder لبناء استعلامات قوية ومرنة.

📩 هل تحتاج مساعدة في إدارة قواعد البيانات؟

Laravel Database Migrations Schema Builder Database Management MySQL
قسم المقالة
Laravel

Database Migrations في Laravel: إدارة قواعد البيانات بكفاءة

دليل شامل للـ Database Migrations في Laravel، كيفية إنشاء وإدارة هيكل قاعدة البيانات مع أفضل الممارسات والأمثلة العملية.

Database Migrations في Laravel: إدارة قواعد البيانات بكفاءة
01

التواصل والاستشارة

تواصل مباشر عبر الواتساب أو الهاتف لفهم احتياجات مشروعك بدقة.

02

التخطيط والجدولة

وضع خطة عمل واضحة مع جدول زمني محدد لكل مرحلة من المشروع.

03

البرمجة والتطوير

تطوير المشروع بأحدث التقنيات لضمان الأداء والأمان العاليين.

04

المراجعة والتسليم

ختبار شامل ومراجعة دقيقة قبل التسليم النهائي للمشروع.

علاء عامر
علاء عامر

مطور ويب محترف بخبرة تزيد عن 10 سنوات في بناء حلول رقمية مبتكرة.

هل تحتاج هذه الخدمة؟

تواصل معي الآن للحصول على استشارة مجانية وعرض سعر

تواصل عبر واتساب رضاكم هو هدفنا الأسمى

عروض إضافية

  • صيانة وتحديث المواقع

    نحافظ على موقعك آمنًا ومحدّثًا دائمًا

  • ربط الأنظمة وواجهات البرمجة

    نربط أنظمتك بواجهات برمجية قوية ومرنة

  • تصميم وتحسين قواعد البيانات

    استعلامات أسرع وهيكلة أوضح وأخطاء أقل

  • تأمين المواقع والحماية المتقدمة

    حماية موقعك من التهديدات السيبرانية

  • أتمتة العمليات والمهام البرمجية

    نؤتمت المهام المتكررة ونوفّر وقتك دائمًا

لديك استفسار؟

اتصل بنا الآن

00201014714795

راسلنا عبر البريد الإلكتروني

[email protected]