PHP code example of sofa / laravel-history

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

    

sofa / laravel-history example snippets


return [
    /**
     * Model of the User performing actions and recorded in the history.
     *
     * @see \Sofa\History\History::user()
     */
    'user_model' => 'App\Models\User',

    /**
     * Custom user resolver for the actions recorded by the package.
     * Should be callable returning a User performing an action, or their raw identifier.
     * By default auth()->id() is used.
     *
     * @see \Sofa\History\HistoryListener::getUserId()
     */
    'user_resolver' => null,

    /**
     * **RETENTION** 

// User model
public function auditLog()
{
    return $this->hasMany(History::class, 'user_id');
}

// Then
$auditLog = auth()->user()->auditLog()->paginate();

    // original relations:
    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
    
    
    // change to:
    public function categories()
    {
        return $this->belongsToMany(Category::class)->using(\Sofa\History\PivotEvents::class);
    }
    
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable')->using(\Sofa\History\MorphPivotEvents::class);
    }
    

   // this will work:
   public function lastComment()
   {
       return $this->hasOne(Comment::class)->latest('id')->whereIn('status', ['approved', 'pending']);
   }
   
   // this will not work (currently...):
   public function lastComment()
   {
       return $this->hasOne(Comment::class) // no ordering
           ->where(fn ($q) => $q->where(...)->orWhere(...)); // unsupported where clause
   }
   
bash
php artisan vendor:publish --provider="Sofa\History\HistoryServiceProvider"
php artisan migrate
 php
$postFromThePast = History::recreate(Post::class, $id, '2020-12-10', ['categories']);
// or: $postFromThePast = Post::recreate($id, '2020-12-10', ['categories']);

// model attributes as of 2020-12-10:
$postFromThePast->title;

// relations as of 2020-12-10:
$postFromThePast->categories->count()

// related models attributes also as of 2020-12-10:
$postFromThePast->categories->first->name;