Skip to content

Instantly share code, notes, and snippets.

@marvinosswald
Created August 21, 2015 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marvinosswald/3d9d8ff4b47fa0b96c84 to your computer and use it in GitHub Desktop.
Save marvinosswald/3d9d8ff4b47fa0b96c84 to your computer and use it in GitHub Desktop.
Many to many attach doesn't work...
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateServiceShopTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('service_shop', function (Blueprint $table) {
$table->increments('id');
$table->integer('serviceId')->unsigned()->index();
$table->foreign('serviceId')->references('id')->on('services')->onDelete('cascade');
$table->integer('shopId')->unsigned()->index();
$table->foreign('shopId')->references('id')->on('shops')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('service_shop');
}
}
<?php
// The model php file /app/Models/Shop.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
public function services()
{
return $this->belongsToMany('\App\Models\Service','service_shop','serviceId','shopId')->withTimestamps();
}
}
//This file response to my api endpoint
//The important part:
$shop = new \App\Models\Shop;
$shop->shopId = $request->input('shop_id');
$shop->language = $request->input('language');
$shop->token = $request->input('token');
$shop->save();
$shop->services()->attach($service->id);
// But the attach method doesn't do a thing...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment