Skip to content

Instantly share code, notes, and snippets.

@zgabievi
Last active October 28, 2016 11:08
Show Gist options
  • Save zgabievi/c1091f9975d14b13dc1ce5f0cde27800 to your computer and use it in GitHub Desktop.
Save zgabievi/c1091f9975d14b13dc1ce5f0cde27800 to your computer and use it in GitHub Desktop.
Laravel “Many To Many Polymorphic Relations”
<?php
namespace App;
class Album {
/**
* Get all of the orders for the book.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
*/
public function orders()
{
return $this->morphToMany(Order::class, 'orderable');
}
}
<?php
namespace App;
class Book {
/**
* Get all of the orders for the book.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
*/
public function orders()
{
return $this->morphToMany(Order::class, 'orderable');
}
}
<?php
namespace App;
class Order {
/**
* Get all of the albums that are assigned this order.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
*/
public function albums()
{
return $this->morphedByMany(Album::class, 'orderable');
}
/**
* Get all of the books that are assigned this order.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
*/
public function books()
{
return $this->morphedByMany(Book::class, 'orderable');
}
}

books

id title
1 Example

orders

id user_id amount
1   1 100.00

orderables

id order_id orderable_id orderable_type
1 1 1 App\Book
<?php
Route::get('test', function() {
$order = \App\Order::findOrFail(1);
return $order->books;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment