PHP code example of dandelionmood / laravel-relatable

1. Go to this page and download the library: Download dandelionmood/laravel-relatable 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/ */

    

dandelionmood / laravel-relatable example snippets


// The `Post` class uses the `HasRelatedContent` trait
$post = Post::find(1);

$anotherPost = Post::find(2);
$person = Person::find(1);

$post->relate($anotherPost);
$post->relate($person);

$related = $post->related;
// => Collection containing `$anotherPost` and `$person`

// config/app.php
'providers' => [
    // ...
    Spatie\Relatable\RelatableServiceProvider::class,
];

use Illuminate\Database\Eloquent\Model;
use Spatie\Relatable\HasRelatedContent;

class Post extends Model
{
    use HasRelatedContent;
}

$post->relate($anotherPost);
$post->relate($anotherPost->id, Post::class);

$post->unrelate($anotherPost);
$post->unrelate($anotherPost->id, Post::class);

// Relate all magic posts
$post->syncRelated(Post::where('magic', true)->get());

// Relate post #1
$post->syncRelated([['id' => 1, 'type' => Post::class]]);

// Relate all magic posts, without detaching other related content
$post->syncRelated(Post::where('magic', true)->get());

$post->related; // : \Illuminate\Support\Collection

$post->loadRelated(); // : \Illuminate\Support\Collection

$post->hasRelated(); // : bool
bash
php artisan vendor:publish --provider="Spatie\Relatable\RelatableServiceProvider" --tag="config"
bash
php artisan vendor:publish --provider="Spatie\Relatable\RelatableServiceProvider" --tag="migrations"
php artisan migrate