Search code examples
laravel-5eloquentmany-to-manyattachmentrecord

How to create a new many to many record with attach


Okey, i seen some posts about this but i don't understand the concept of attach at all, i have three tables:

Llistes(Lists):

        $table->increments('id');
        $table->string('nom_llista');
        $table->integer('user_id')->unsigned();
    });

Cancons(Songs):

        $table->increments('id');
        $table->string('titol');
        $table->integer('genere_id')->unsigned();
        $table->integer('artista_id')->unsigned();
        $table->integer('album_id')->unsigned();

Pivot table: llistes_cancons (lists_songs):

        $table->increments('id');
        $table->integer('id_canco')->unsigned();
        $table->integer('id_llista')->unsigned();
        $table->timestamps();

I have two other Classes that i think that are correct, but i''m not sure:

In Canco.php (Song.php):

public function llistescancons_llistes()
{
    return $this->belongsToMany('App\Llista');
}

In Llista.php (List.php):

public function llistescancons_cancons()
{
    return $this->belongsToMany('App\Canco');
}

So, the question is how can I implement in my controller a function that let me add new record to the pivot table (many to many) and if it's possible another funtion to show the records, i'm newbie in Laravel and it's a bit hard for me.


Solution

  • There's no need to implement methods to add/remove records from the pivot table. Eloquent has attach/detach methods that can do that for you, but first you need to give Eloquent the column names of the pivot table since you are not using Eloquent's column name convention.

    In Canco.php (Song.php):

    public function llistescancons_llistes()
    {
        return $this->belongsToMany('App\Llista','llistes_cancons','id_canco','id_llista');
    }
    

    In Llista.php (List.php):

    public function llistescancons_cancons()
    {
        return $this->belongsToMany('App\Canco','llistes_cancons','id_llista','id_canco');
    }
    

    Then if you want to attach a song to list, you can easily use the song id to do that

    $list = App\Llista::find(1);
    $list->llistescancons_cancons()->attach($songId);
    

    or the other way around

    $song = App\Canco::find(1);
    $song->llistescancons_llistes()->attach($listId);