Skip to content

Instantly share code, notes, and snippets.

@AlexeyRudkovskiy
Created October 21, 2016 21:54
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 AlexeyRudkovskiy/9fb4fcfd3efcb93ad825f73a695dc463 to your computer and use it in GitHub Desktop.
Save AlexeyRudkovskiy/9fb4fcfd3efcb93ad825f73a695dc463 to your computer and use it in GitHub Desktop.
Laravel belongsToMany
<?php
/*
* database/migrations/2016_10_21_214304_create_products_table.php
*/
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('products');
}
}
<?php
/*
* database/migrations/2016_10_21_214309_create_categories_table.php
*/
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('categories');
}
}
<?php
/*
* database/migrations/2016_10_21_214645_create_category_product_table.php
*/
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoryProductTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('category_product', function (Blueprint $table) {
$table->integer('product_id')->unsigned();
$table->integer('category_id')->unsigned();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('category_product');
}
}
<?php
/*
* app/Category.php
*/
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function products()
{
return $this->belongsToMany(Product::class);
}
}
<?php
/*
* app/Product.php
*/
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment