Thursday, March 2, 2017

Laravel Relation with Pivot Table, Relationships?

I have a User-Tables aswell as an "Adress" Table. They can enter multiple Adresses to choose from when checking out.

Now I want to be able to have one adress set as the standard invoice adresse and another one as the standard invoise adress. I thought about doing it using a pivot table, containing the following:

Schema::create('users_adresses_pivot', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->integer('invoice_adress_id')->unsigned();
        $table->foreign('invoice_adress_id')->references('id')->on('adresses');
        $table->integer('delivery_adress_id')->unsigned();
        $table->foreign('delivery_adress_id')->references('id')->on('adresses');
        $table->timestamps();
    });

However I'm not sure if thats the right way. It looks a bit like a bad practice to me. If I choose this option how do I set the Relations? Because I would need two Relations from User to Adresses. I already got one in order to foreach through them in a view. So If I replaced that with the Pivot Relation I could only get the standard invoice & delivery adresses instead of the others too. Any idea?

This is my current Relationship: User.php:

public function adresses()
    {
        return $this->hasMany('App\Adress');
    }

Adress.php:

 public function user()
    {
        return $this->belongsTo('App\User');
    }




via Scarwolf

Advertisement