PHP code example of fidum / laravel-eloquent-morph-to-one
1. Go to this page and download the library: Download fidum/laravel-eloquent-morph-to-one library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
fidum / laravel-eloquent-morph-to-one example snippets
namespace App;
use Fidum\EloquentMorphToOne\HasMorphToOne;
use Fidum\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');
}
}