Created
January 17, 2022 15:27
-
-
Save dominiquevienne/d186986c5dce5a486a51391a78ab424e to your computer and use it in GitHub Desktop.
Polymorphic relations between User, Product and Country in Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Models; | |
use Illuminate\Database\Eloquent\Factories\HasFactory; | |
use Illuminate\Database\Eloquent\Model; | |
class Country extends Model | |
{ | |
use HasFactory; | |
protected $fillable = [ | |
'name', | |
'capital', | |
]; | |
public function countryable() | |
{ | |
return $this->morphTo(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Models; | |
use Illuminate\Database\Eloquent\Factories\HasFactory; | |
use Illuminate\Database\Eloquent\Model; | |
class Product extends Model | |
{ | |
use HasFactory; | |
protected $fillable = [ | |
'name', | |
'price', | |
]; | |
public function origin() | |
{ | |
return $this->morphOne(Country::class, 'countryable'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Models; | |
use Illuminate\Database\Eloquent\Factories\HasFactory; | |
use Illuminate\Database\Eloquent\Model; | |
class User extends Model | |
{ | |
use HasFactory; | |
protected $fillable = [ | |
'firstname', | |
'lastname', | |
]; | |
public function nationality() | |
{ | |
return $this->morphOne(Country::class, 'countryable'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment