Search code examples
laravelmany-to-manypivot-table

Laravel Many-to-Many Pivot Table


I have a fairly simple question about the use of Pivot tables in laravel. Firstly ill give some information about my situation, I have two tables name "Vehicles", and "Events". Now I would like to create a table that will be used to hold vehicles that have registered for an event. Now the relationship that between these two tables would be that "Many Vehicles can register for Many Events" and vice versa. would a Pivot table be the best way to accomplish this, and if so could more singular values be in the same table?


Solution

  • You can associate an event with multiple vehicles and a vehicle to multiple events by doing something like this with your models (not tested):

    Vehicle.php

    <?php
    
    namespace App;
    
    use App\Event;
    use Illuminate\Database\Eloquent\Model;
    
    class Vehicle extends Model
    {
    
        ...
    
    
        /**
         * Get the events that this vehicle belongs to.
         *
         * @return \App\Event
         */
        public function events()
        {
            return $this->belongsToMany(Event::class, 'vehicle_event');
        }
    }
    

    Event.php

    <?php
    
    namespace App;
    
    use App\Vehicle;
    use Illuminate\Database\Eloquent\Model;
    
    class Event extends Model
    {
    
        ...
    
    
        /**
         * Get the vehicles that this event has.
         *
         * @return \App\Vehicle
         */
        public function events()
        {
            return $this->hasMany(Vehicle::class, 'vehicle_event');
        }
    }
    

    You'll also need a migration file for the pivot table:

        ...
    
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('vehicle_event', function(Blueprint $table)
            {
                $table->integer('vehicle_id')->unsigned()->index();
                $table->foreign('vehicle_id')->references('id')->on('vehicles');
                $table->integer('event_id')->unsigned()->index();
                $table->foreign('event_id')->references('id')->on('events');
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('vehicle_event');
        }
    
        ...
    

    Then you can to use attach() and detach() to associate vehicles with events or vice versa.