<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
jodeveloper / laravel-eloquent-morph-to-one example snippets
namespace App;
use JoDeveloper\EloquentMorphToOne\HasMorphToOne;
use JoDeveloper\EloquentMorphToOne\MorphToOne;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
class Post extends Model
{
use HasMorphToOne;
public function featuredImage(): MorphToOne
{
return $this->morphToOne(Image::class, 'imageable')
->wherePivot('featured', 1);
//->withDefault();
}
public function images(): MorphToMany
{
return $this->morphToMany(Image::class, 'imageable')
->withPivot('featured');
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
class Image extends Model
{
public function posts(): MorphToMany
{
return $this->morphedByMany(Post::class, 'imageable');
}
public function videos(): MorphToMany
{
return $this->morphedByMany(Video::class, 'imageable');
}
}