Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Blog: Unique Pivot Rows With Laravel's Eloquent
<?php
use App\Models\User;
use App\Models\Forum;
//I prefer to use App::make to instantiate objects
$user = App::make('App\Models\User');
$user->first_name = 'Joe';
$user->last_name = 'Smith';
$user->email = 'jsmith@email.com';
$user->save();
//Relate user to forums #1 and #2
$user->forums()->sync([1,2], false);
//----------------------
//Sometime later we need to add the user to more forums
$user->forums()->sync([1,3], false);
//The result of the sync above is:
// - the relation to forum #3 will be created
// - the relation to forums #1 and #2 will be left alone
<?php
use App\Models\User;
use App\Models\Forum;
$user = User::find(1);
//Arrange our data so the keys are forum_ids and the values are
//an associative array of data for the pivot table
$data = [
1 => ['access_level' => 'Member'],
3 => ['access_level' => 'Admin'],
4 => ['access_level' => 'Admin']
];
//Sync the data
$user->forums()->sync($data, false);
//The result of the sync above is:
// - the relation of the user to forums #1 and #3 being updated with an
// access_level of Member and Admin, respectively
// - the relation to forum #4 will be created and the pivot table's
// access_level column will read Admin.
// - the relation to forum #2, created previously, will remain unchanged
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateForumUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('forum_user', function ($table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('forum_id')->unsigned();
$table->string('access_level')->default('Member');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('forum_id')->references('id')->on('forums');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('forum_user');
}
}
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateForumUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('forum_user', function ($table) {
$table->integer('user_id')->unsigned();
$table->integer('forum_id')->unsigned();
$table->string('access_level')->default('Member');
$table->timestamps();
//Make the user_id/forum_id combo the primary key
$table->primary(['user_id', 'forum_id']);
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('forum_id')->references('id')->on('forums');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('forum_user');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment