PHP code example of c-tanner / laravel-deep-sync

1. Go to this page and download the library: Download c-tanner/laravel-deep-sync 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/ */

    

c-tanner / laravel-deep-sync example snippets


#[ObservedBy([DeepSync::class])]
class User extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = [
        'name',
        'is_active'
    ];

    // Properties that trigger DeepSync
    public $syncable = ['is_active'];

    #[SyncTo]
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class, 'author_id');
    }
}

#[ObservedBy([DeepSync::class])]
class Post extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = [
        'title',
        'body',
        'author_id',
        'is_active'
    ];

    // Properties that trigger DeepSync
    public $syncable = ['is_active'];

    #[SyncFrom]
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'author_id');
    }
}

class Task {
    return subtasks(): HasMany
        return $this->hasMany(Subtask::class);
    }
}

#[ObservedBy([DeepSync::class])]
class Task extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = [
        'name',
        'is_complete'
    ];

    public $syncable = ['is_complete'];

    #[SyncFrom]
    public function subtasks(): HasMany
    {
        return $this->hasMany(Subtask::class);
    }
}

#[ObservedBy([DeepSync::class])]
class Subtask extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = [
        'name',
        'is_complete',
        'task_id'
    ];

    public $syncable = ['is_complete'];

    #[SyncTo]
    public function task(): BelongsTo
    {
        return $this->belongsTo(Task::class);
    }
}

public function test_reverse_sync()
{
    $task = Task::factory()->has(
        Subtask::factory(3)->state(
            function(array $attributes, Task $task) {
                return [
                    'task_id' => $task->id
                ];
            }
        )
    )->create();

    $this->assertEquals(1, Task::count());
    $this->assertEquals(3, Subtask::count());
    $this->assertEquals(3, Task::find($task->id)->subtasks()->count());

    // Task only becomes complete when all subtasks are complete
    
    $subtask1 = Subtask::find(1);
    $subtask1->update(['is_complete' => 1]);

    $this->assertEquals(0, Task::find($task->id)->is_complete);

    $subtask2 = Subtask::find(2);
    $subtask2->update(['is_complete' => 1]);

    $this->assertEquals(0, Task::find($task->id)->is_complete);

    $subtask3 = Subtask::find(3);
    $subtask3->update(['is_complete' => 1]);

    $this->assertEquals(1, Task::find($task->id)->is_complete);
    
}