Giter Site home page Giter Site logo

revisionable's Introduction

Sofa/Revisionable

Code quality Latest Stable Version Downloads

Nice and easy way to handle revisions of your db.

  • Handles the revisions in bulk - one entry covers all the created/updated fields, what makes it really easy to eg. compare 2 given versions or get all the data changed during single action.

Requirements

  • This package requires PHP 5.4+
  • Currently it works out of the box with Laravel5 + generic Illuminate Guard, tymon/jwt-auth OR cartalyst/sentry 2/sentinel 2

Usage (Laravel5 basic example - see Customization below as well)

1. Download the package or require in your composer.json:

composer require sofa/revisionable

2. Add the service provider to your app/config/app.php:

    'providers' => array(

        ...

        'Sofa\Revisionable\Laravel\ServiceProvider',
    ),

3. Publish the package config file:

~$ php artisan vendor:publish [--provider="Sofa\Revisionable\Laravel\ServiceProvider"]

this will create config/sofa_revisionable.php file, where you can adjust a few settings:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | User model (for executor relation on Revision model).
    |--------------------------------------------------------------------------
    |
    | By default App\User.
    */
    'usermodel' => 'App\User',

    /*
    |--------------------------------------------------------------------------
    | User provider (auth) implementation.
    |--------------------------------------------------------------------------
    |
    | By default Laravel generic Illuminate\Auth\Guard.
    |
    | Supported options:
    |  - illuminate
    |  - sentry
    |  - sentinel
    |  - jwt-auth
    |  - session 
    */
    'userprovider' => 'illuminate',


    /*
    |--------------------------------------------------------------------------
    | User field to be saved as the author of tracked action.
    |--------------------------------------------------------------------------
    |
    | By default:
    |
    |  - id for illuminate
    |  - login field (email) for sentry/sentinel
    */
    'userfield' => 'id',


    /*
    |--------------------------------------------------------------------------
    | Table used for the revisions.
    |--------------------------------------------------------------------------
    */
    'table' => 'revisions',


    /*
    |--------------------------------------------------------------------------
    | Database connection used for the revisions.
    |--------------------------------------------------------------------------
    */
    'connection' => null,

];

4. Run the migration in order to create the revisions table:

~$ php artisan revisions:table
~$ php artisan revisions:upgrade-5.3
~$ php artisan migrate [--database=custom_connection]

You can provide additional --database param if you want the migration to be run using non-default db connection.

5. Add revisionable trait to the models you wish to keep track of:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;
use Sofa\Revisionable\Laravel\Revisionable; // trait

class User extends Model
{
    use Revisionable;

    /*
     * Set revisionable whitelist - only changes to any
     * of these fields will be tracked during updates.
     */
    protected $revisionable = [
        'email',
        'name',
    ];

And that's all to get your started!

Customization in L5

Default behaviour:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Sofa\Revisionable\Laravel\Revisionable;

class Ticket extends Model
{
    use Revisionable;
}
$ php artisan tinker

>>> $ticket = App\Models\Ticket::first();
=> <App\Models\Ticket>

>>> $revision->getDiff();
=> [
       "customer_id"    => [
           "old" => "1",
           "new" => "101"
       ],
       "item_id"        => [
           "old" => "2",
           "new" => "1"
       ],
       "responsible_id" => [
           "old" => "8",
           "new" => "2"
       ]
   ]

>>> $revision->old('item_id');
=> "2"

>>> $revision->new('item_id');
=> "1"

>>> $revision->isUpdated('item_id');
=> true

>>> $revision->isUpdated('note');
=> false

>>> $revision->label('item_id');
=> "item_id"

>>> $revision->old;
=> [
       "defect"         => "nie dziala",
       "note"           => "wrocilo na gwarancji",
       "customer_id"    => "1",
       "item_id"        => "2",
       "responsible_id" => "8",
       "status_id"      => "6"
   ]

>>> $revision->action;
=> "updated"

But here's where you can leverage bundled Presenter in order to make useful adjustments:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Sofa\Revisionable\Laravel\Revisionable;

class Ticket extends Model
{
    use Revisionable;

    protected $revisionPresenter = 'App\Presenters\Revisions\Ticket';
}
namespace App\Presenters\Revisions;

use Sofa\Revisionable\Laravel\Presenter;

class Ticket extends Presenter
{
    protected $labels = [
        'item_id'        => 'Przedmiot',
        'customer_id'    => 'Klient',
        'status_id'      => 'Status',
        'responsible_id' => 'Serwisant',
        'defect'         => 'Usterka',
        'note'           => 'Uwagi',
    ];

    protected $passThrough = [
        'item_id'        => 'item.name',
        'customer_id'    => 'customer.name',
        'responsible_id' => 'serviceman.name',
        'status_id'      => 'status.name',
    ];

    protected $actions = [
        'created'  => 'utworzony',
        'updated'  => 'edytowany',
        'deleted'  => 'usunięty',
        'restored' => 'przywrócony',
    ];

}

then

$ php artisan tinker

>>> $ticket = App\Models\Ticket::first();
=> <App\Models\Ticket>

>>> $revision->old('item_id'); // value fetched from the relationship
=> "komputer pc"

>>> $revision->new('item_id'); // value fetched from the relationship
=> "laptop acer"

>>> $revision->label('item_id'); // custom label defined in the presenter
=> "Przedmiot"

>>> $revision->action; // custom action name defined in the presenter
=> "edytowany"

revisionable's People

Contributors

daryledesilva avatar developeritsme avatar jarektkaczyk avatar omranic avatar sbreiler avatar sbtsrbayer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

revisionable's Issues

Getting exception while publishing vendor files.

Here's the screenshot I'm getting while excuting

php artisan vendor:publish --provider="Sofa\Revisionable\Laravel\ServiceProvider"

image

Using composer require sofa/revisionable ~2.0 as per Readme.md on branch 5.3

Anyway after playing around, I have tried composer require sofa/revisionable which downloads branch 5.3 and the artisan vendor:publish command works fine but I'm confused which branch should I use, since on branch 5.3 the Readme.md state to use 2.0 branch.

Using PK as string and composite PK

Hello,

I am in need to log the changes to my db models, the thing is I am working in an existing DB that uses mostly varchar and composite keys, example:

payments:

employee_number VARCHAR(6) = 000010
date VARCHAR(8)=20160101
amount DOUBLE= 205.00

PK (employee_number , date)

Is there a way to support this?

Binary field implicit conversion

Would it be safe to use text field instead of binary fields for revisionable old and new columns?

With binary fields sql server gives an error about implicit conversion.

Next exception 'Illuminate\Database\QueryException' with message 'SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]
Implicit conversion from data type nvarchar to varbinary(max) is not allowed. 
Use the CONVERT function to run this query. 
(SQL: insert into [revisions] (...

I'm quessing this is yet another place where sql server is more strict in its default config then mysql.

Show diff between old and new revision after deleting

After deleting model getDiff() return empty array.

Now in revisionable/src/Laravel/Revision.php:

/**
 * Get array of updated fields.
 *
 * @return array
 */
public function getUpdated()
{
    return array_keys(array_diff_assoc($this->new, $this->old));
}

I think should be:

/**
 * Get array of updated fields.
 *
 * @return array
 */
public function getUpdated()
{
    return array_keys(array_diff_assoc($this->new, $this->old)) ?: array_keys(array_diff_assoc($this->old, $this->new));
}

False returned by listener stops propogation of the event to other listeners.

Ran into this issue while disabling the revisions on one model with $this->disableRevisioning(), which had other listeners attached to it by another trait.

The on[Event] methods in revisionable/src/Laravel/Listener.php will return the result of the $this->log() method. When this returns false (in the case of $this->disableRevisioning()), laravel will not propogate the event to other listeners. Also onUpdated() does the same when there's no diff.

Strange error

Hello i get this error, do you know why this can happen?

FatalErrorException in RevisionableTrait.php line 297: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

    in RevisionableTrait.php line 297
    at HandleExceptions->fatalExceptionFromError(array('type' => '4', 'message' => 'syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'', 'file' => 'C:\xampp\htdocs\l5\vendor\sofa\revisionable\src\Laravel\RevisionableTrait.php', 'line' => '297')) in HandleExceptions.php line 116
    at HandleExceptions->handleShutdown()



The code that used to call this is


<?php

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Sofa\Revisionable\Laravel\RevisionableTrait;


class User extends BaseModel implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    // use the trait
    use RevisionableTrait;

    // Set revisionable whitelist - only changes to any
    // of these fields will be tracked during updates.
    protected $revisionable = [
        'email',
        'username',
        'first_name',
        'last_name',
        'name',
        'last_login',
        'last_login_ip',
        'created_by',
        'edited_by',
        'username',
        'password',
        'email',
        'is_active',
        'is_admin',
        'is_verified',
        'is_public',
        'oauth_uid',
        'oauth_provider'
    ];

    // Or revisionable blacklist - if $revisionable is not set
    // then you can exclude some fields from being tracked.
    protected $nonRevisionable = [
        'created_at',
        'updated_at',
    ];




    //protected $hidden = array('password', 'remember_token');
    protected $fillable = array(
        'updated_at',
        'created_at',
        'expires_on',
        'last_login',
        'last_login_ip',
        'created_by',
        'edited_by',
        'username',
        'password',
        'email',
        'is_active',
        'is_admin',
        'is_verified',
        'is_public',
        'basic_mode',
        'first_name',
        'last_name',
        'thumbnail',
        'parent_id',
        'api_key',
        'user_information',
        'subscr_id',
        'role',
        'medium',
        'oauth_uid',
        'oauth_provider',
        'profile_url',
        'website_url'

    );

// ....................

My config is

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | User provider (auth) implementation.
    |--------------------------------------------------------------------------
    |
    | By default Laravel generic Illuminate\Auth\Guard.
    |
    | Supported options:
    |  - illuminate
    |  - sentry
    */
    'userprovider' => 'illuminate',


    /*
    |--------------------------------------------------------------------------
    | User field to be saved as the author of tracked action.
    |--------------------------------------------------------------------------
    |
    | By default:
    |
    |  - id for illuminate
    |  - login field (email) for sentry
    */
    'userfield'    => 'id',


    /*
    |--------------------------------------------------------------------------
    | Table used for the revisions.
    |--------------------------------------------------------------------------
    */
    'table'        => 'revisions',


    /*
    |--------------------------------------------------------------------------
    | Templates for the Presenter
    |--------------------------------------------------------------------------
    */
    'templates'    => [

        /*
        |----------------------------------------------------------------------
        | Template for the renderDiff method
        |----------------------------------------------------------------------
        */
        'diff'    => [
            'start' => '<div>',
            'body'  => '<p class="diff-string">'
                .'<span class="diff-key">:key</span>: '
                .'<span class="diff-old">:old</span>&nbsp;&rarr;&nbsp;<span class="diff-new">:new</span>'
                .'</p>',
            'end'   => '</div>',
        ],
    ],
];

'Illuminate\Auth\SessionGuard' does not have a method 'driver'

call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Auth\SessionGuard' does not have a method 'driver'

in AuthManager.php line 288
at HandleExceptions->handleError('2', 'call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Auth\SessionGuard' does not have a method 'driver'', 'C:\Source\starter\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php', '288', array('method' => 'driver', 'parameters' => array()))
at call_user_func_array(array(object(SessionGuard), 'driver'), array()) in AuthManager.php line 288
at AuthManager->__call('driver', array()) in FiveServiceProvider.php line 120
at FiveServiceProvider->Sofa\Revisionable\Laravel{closure}(object(Application), array()) in Container.php line 735
at Container->build(object(Closure), array()) in Container.php line 633
at Container->make('revisionable.userprovider', array()) in Application.php line 697
at Application->make('revisionable.userprovider') in Container.php line 1178
at Container->offsetGet('revisionable.userprovider') in FiveServiceProvider.php line 132
at FiveServiceProvider->Sofa\Revisionable\Laravel{closure}(object(Application), array()) in Container.php line 735
at Container->build(object(Closure), array()) in Container.php line 633

Support for Laravel 5.5

On Laravel 5.5, ServiceProvider is not needed to be registered in app.php
Also, fire() method is changed into handle().

It would be nice to see this plugin at 5.5 too :)

User is registered as '--'

Hey,

First of all, thx for this package!

I got it almost working in my application, the only thing it doesn't do is record the user that made the change. I'm using the default Illuminate Auth provider, but that gives me an integer of the user ID. Which is being ignored and results in the '--'.

Actually, i would like to save the user ID in stead of the name, could you help me out to get that working?

By the way, i'm using tag 0.1.6.

Hope to hear from you,

Kind regards,

Martin

The revisions table only saves the created entry

I set up revisions on a model Tickets

use Sofa\Revisionable\Revisionable;
use Sofa\Revisionable\Laravel\RevisionableTrait;

class Tickets extends Model implements Revisionable  {

    use RevisionableTrait;
        protected $revisionable = array(
        'stage_id',
        'assigned_to',
        'updated_at',
    );

But, any revisions on this table are not stored in revisions table. Only the newly created entry are stored. When I update stage_id, nothing is stored in revisions table.

Ambiguous class resolution warning

Each time I run a composer command, I always get this warning with this particular package:

Warning: Ambiguous class resolution, "CreateSofaRevisionsTable" was found in both "$baseDir . '/database/migrations/2015_03_05_000000_create_sofa_revisions_table.php" and "/home/dev/vendor/sofa/revisionable/src/migrations/2015_03_05_000000_create_sofa_revisions_table.php", the first will be used.

It's not overly important since it's loading the correct one, but still should be fixed so a warning doesn't pop up every time I run a composer command.

History not maintained in revisions table

Hi, I am using laravel 4.2 i have done all the steps that you have mentioned, when i update a record through model it is not updating in the revisions table. i dont know what i have to do make it work.

Not able to get the Labels from presenters

I have this Labels array in presenters file:

protected $labels = [
        'stage_id'      => 'Changed Ticket Stage From',
        'assigned_to'   => 'Assigned Ticket From',
];

I am trying to get the labels for 'stage_id'

$ticket = Tickets::find($id);
$revisions = $ticket->revisions()->get();
print_r($revisions[0]->label('stage_id'));

but, this only prints 'stage_id', and not the string that I need.

What could be the issue with this?

Error

I'm using Laravel 4.2 and getting this error while I moved to another system
[2015-03-13 00:17:18] production.ERROR: exception 'ErrorException' with message 'Argument 1 passed to Sofa\Revisionable\Laravel\Listener::onCreated() must be an instance of Sofa\Revisionable\Revisionable, instance of ProductTag given' in /Users/param/Documents/code/LookManagerApi/vendor/sofa/revisionable/src/Laravel/Listener.php:32
Stack trace:

Pushing up version number

Hello Dear Jarek,

First of all thank you for this piece of art package, it really helped much in our projects.

This isn't an issue, just asking you to push up the version number so the latest updates could be fetched from the composer since it still sees old versions 1.0.1/0.2.2 which already cached on packagist & locally.
Again, thank you for your hard work, keep up the good work +1

Sincerely Regards
Abdelrahman Omran

Push Notifications

I want to build a notification system for my Laravel+AngularJS app for monitoring the changes happening in the system say "New Product has been added into the system". I'm using revisionable package for the same which keeps tracks of all the changes and updates in a table. Now I want to use websockets to implement Push Notifications but again I need to monitor that revisions table to fire notification on the events. How this can be achieved

php artisan vendor:publish error

$ php artisan vendor:publish --provider="Sofa\Revisionable\Laravel\FiveServiceProvider"
PHP Fatal error: Call to undefined method Sofa\Revisionable\Laravel\FiveServiceProvider::publishes() in /Users/param/Documents/code/LookManagerApi/vendor/sofa/revisionable/src/Laravel/FiveServiceProvider.php on line 25
{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Call to undefined method Sofa\Revisionable\Laravel\FiveServiceProvider::publishes()","file":"/Users/param/Documents/code/LookManagerApi/vendor/sofa/revisionable/src/Laravel/FiveServiceProvider.php","line":25}}

Laravel 5.1 is not supported

Not Really an issue, just wanted to know if this module supports Laravel 5.1 or not. As I am not able to integrate it with my Project (laravel 5.1.x)
v5.4 is not supported with L5.1
error is in serviceprovide.php line 144.

screen shot 2017-06-09 at 5 56 01 pm

Presenter not working

None of the methods of the Presenter seems to be working. Errors not thrown. Tried with vanila example in readme.

different database connection

Hi,

my revisions table is on a different db connection then the default. How can I set the connection on the Revision model? I don't see any option in the config for that.

Bug when relying simply just on latest()

If you do a create and then shortly after a delete or an update the created_at timestamp will be the same therfore

    public function latestRevision()
    {
        return $this->hasOne('Sofa\Revisionable\Laravel\Revision', 'row_id')
            ->where('table_name', $this->getTable())
            ->latest();
    }

using simply latest() will yield incorrect results... i think it should sort by created_at and also the id.

Log just the diff of data alterations, don't log all fields every time

Is possible to store just the diff of data modifications, maybe with a configurable flag parameter to define if will store the diff or full model data?

Here we have some big text fields that need to be logged, but it's not always altered and other fields that are altered a lot of times every day.

I'm working with PHP + Laravel since 1 month ago, but I can try to help if it's possible!

How to get the 'Name' of user from the revisions table?

$ticket = App\Tickets::find(14);
$revisions = $ticket->latestRevision;

How do I get the details of the user who is responsible for this revision. I see that in revision table, column user stores the user_id. How do I get it from the $revisions variable??

Is this packages supportable for laravel 4.0

When i tried this package with laravel 4.0 i got this error when i was going to publish the config

$ php artisan config:publish sofa/revisionable
{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","me
ssage":"Call to undefined method Illuminate\Foundation\Application::bindShared
()"
)

is there any way to resolve it, because i desperately need this package.

There are no commands defined in the "vendor" namespace.

Hi, I am just trying to install this package on laravel 4.2, but when I run php artisan vendor:publish [--provider="Sofa\Revisionable\Laravel\ServiceProvider"] I get the error There are no commands defined in the "vendor" namespace.

Which command should I use to configure Revisionable?

Regards.

--

Oops, forget it, with php artisan config:publish sofa/revisionable is enough.

feature request: changing user on recording

i'm tracking a table with revisionable.

but sometimes, system makes changes on table, when user logged in.

for detailed example,

  • user, creates a new record for [x table]
  • when user creates record for x table, automated system creates some records for [y table]
  • user can change records on y table.

so i'm tracking y table for any change. but, it tracks system changes as user. so, we need to change user row for revisionable.

$xModel = new xModel();
$xModel->revisionable->user = 'system';
$xModel->name = 'asdkasds';
$xModel->save();

(thats just an example, i know thats a bad example, but example :))

thanks.

Differences between branches master and 1.0

Hello Jarek, how are you?

It's not exactly an issue, I think, but I'm confused about this. I have a question about actual branches (master and 1.0).

Recently I'd asked you about L4.2 and L5 support, and L4.2 is just in dev-master (packagist). I saw that 1.0 has for example "Presenter->labels", that not exists in dev-master.

What the logic of these branches, and how do you plan to continue with these?

Currently I need the "labels" and "passThrough" but I'm using dev-master because we use L4.2 here.

Thank you very much for your work, it help us a lot here! 👍 As I said, I intend to continue helping you with this project, always as I can.

Regards,
Carlos

How to trigger a revision for a custom method from a Controller?

Idea: log an action, that is not neither Create/Update/Delete.

I posted a question on StackOverflow related to this idea.

Example:
An user sends an email (this action doesn't CRUD any model), but I want to track this action. So I do something like:
Action::make('send email', $user, $email, $time, $from, $to, $subject, ....)

So, can this be done with this package ?

HTML field redered on revision->renderDiff()

Consider a field where you store html elements or any other text element. Consider that you stored a wrong html on it. The rederDiff() will present the diff to the browser as html to be parsed.

I discovered this issue modifying a text field into a html tag without closing it. That broke my layout.

Update event doesn't fire with Http (Created, Deleted & Restored work fine)

I'm using Laravel 5.0, composer resolves to 1.0.x-dev.

Other three events all behave as I'd expect, and the old/new/diff shows I've got the protected $revisionable fields right..

The event seems to be registered:

use Clientname\Models\User

User::getRevisionableEvents()
=> [
       "Created",
       "Updated",
       "Deleted",
       "Restored"
   ]

I did some debugging in Laravel/Listener.php ( print(__FUNCTION__);) and found:

>>> $u = User::find(151);
>>> $u->delete();
__constructonDeleted⏎  // as expected
=> true
>>> $u->delete();
=> null   // as expected, no action when you delete the already-deleted!
>>> $u->restore()
__constructonUpdated__constructonRestored⏎  // should both be here?
=> true
>>> $u->update(['name' => 'Bill Foo']);
__constructonUpdated⏎ // ok, great
=> true

and the update command does fire if I do it like that via the Tinker CLI.

So why doesn't it fire for my Http Requests? The other three events do.

// controller method
public function update(UserRepository $user, EditUserRequest $request, $id)
    {
        // ....
        $user->update($request->only($fields), $id);
        // ....
    }

// repository method
public function update(array $data, $id, $attribute = 'id') {
        // ...
        return $this->model->withTrashed()->where($attribute, '=', $id)->update($data);
    }

Ideas appreciated!

Revisionable not saving changes on Laravel 5.1

Hi, I cant seem to get Revisionable to save changes. Here's my model:

namespace App\Models\v1;
use Illuminate\Database\Eloquent\Model;
use Sofa\Revisionable\Laravel\RevisionableTrait;
use Sofa\Revisionable\Revisionable;
class Company extends Model implements Revisionable
{
use RevisionableTrait;
}

  1. The model does not throw any errors. Changes are not saved to the revisions db table.
  2. Also I noticed that Laravel stopped using Eloquent, but this package still extends /Eloquent. Why is this?

Any ideas please?

Trouble with DateTime Object

Hello,
when i try to assign datetime object to a DateTime field it gives error.

ErrorException in RevisionableTrait.php line 187:
Object of class DateTime could not be converted to string

Here is my code
$class = new SomeModel();
$class->some_date = new \DateTime();
$class->save();

some_date field created with schema builder, as dateTime

Update is not being tracked

What would the reason be for a Update not to be tracked... Creating works just fine however

     App\Article::where('id', 1)
          ->update(['author' => "Some New Author"]);

does nothing.

Changes in model not saved in revision table

In my model the create event is recorded fine in revision table but when i edit some column using ajax the changes are stored in database but not in revision table.
`namespace AppName\models;
use Illuminate\Database\Eloquent\Model;
use Sofa\Revisionable\Laravel\RevisionableTrait; // trait
use Sofa\Revisionable\Revisionable; // interface

class Guest_list extends Model implements Revisionable
{
use RevisionableTrait;
//protected $revisionPresenter = 'WeddingOs\Presenters\Revisions\Ticket';

 protected $revisionable = [
    'email_1',
    'first_name',
];
protected $table='guest_list';

}`

*_Controller which is saving the data
*_use Illuminate\Http\Request;

use AppName\Http\Requests;
use AppName\models\Guest_list;
use Auth;

class ExcelEdit extends Controller
{
function ModifyGuestList(Request $request, Guest_list $guest)
{
$colMap = array(0 => 'first_name',1 => 'last_name',2 => 'email_1',3 => 'email_2',4 => 'email_3',5 => 'phone_1',6 => 'phone_2',7 => 'address',8 => 'city',9 => 'state', 10=>'country',10=>'zip_code',11=>'guest_list');

    $changes=$request->input('changes');
    $changed_row=$request->input('changedrow');
    $changesColumn=$colMap[$changes[0][1]-1];
    if($changed_row[0]!='')                 // Checking if row is new or updated
    {

        $guest->where($changesColumn, $old_data)
          ->where('id', $guest_id)
          ->update([$changesColumn => $new_data])->save();

    }
}

}

Polymorphic laravel relations revisions

I want to track the relations existing between my models say a Product has many tags and a tag may belong to many products. How can achieve that which says "this tag has been removed from this product".

Error: latestRevision is Undefined Property

When I run this:
$ticket = App\Tickets::where('ticket_id', '=', 14)->get();

and then:
$revision = $ticket->latestRevision;

I get this error:
PHP error: Undefined property: Illuminate\Database\Eloquent\Collection::$latestRevision on line 1

What is wrong with my approach?

Not tracking revisions under these circunstances

Hello,

Revisionable is 1.0.
Laravel is 5.0.

I noticed that under these circunstances the revisions are not tracked.

When instead of extending Eloquent, I extend Illuminate\Database\Eloquent\Model directly, which is the same (?). Like so:

<?php namespace App\Models;

/**
 * Changes to this model generate a revision entry.
 */
use Sofa\Revisionable\Laravel\RevisionableTrait;
use Sofa\Revisionable\Revisionable;
use Illuminate\Database\Eloquent\Model;


class Representante extends Model implements Revisionable {

  use RevisionableTrait;

  protected $fillable = ['nome', 'telefone', 'email'];
  protected $revisionable = ['nome', 'telefone', 'email'];


  public function clientes()
  {
    return $this->hasMany('App\Models\Cliente');
  }

}

Or when extending a BaseModel, like so:

<?php namespace App\Models;

use Eloquent;
use \Carbon\Carbon;

/**
 * Our base model
 */
class BaseModel extends Eloquent {

  function __construct() {
    Carbon::setLocale('pt_BR');
    Carbon::setToStringFormat('d/m/Y H:i:s');
  }  

}
<?php namespace App\Models;

use Sofa\Revisionable\Laravel\RevisionableTrait;
use Sofa\Revisionable\Revisionable;

class Representante extends BaseModel implements Revisionable {

  use RevisionableTrait;

  protected $fillable = ['nome', 'telefone', 'email'];
  protected $revisionable = ['nome', 'telefone', 'email'];


  public function clientes()
  {
    return $this->hasMany('App\Models\Cliente');
  }

}

It only works if I extend Eloquent directly on the revisionable model class, which doesnt allow me to use a BaseModel. Is there any reason for this that I am not seeing?

Like this, it works perfectly:

<?php namespace App\Models;

use Eloquent;
use Sofa\Revisionable\Laravel\RevisionableTrait;
use Sofa\Revisionable\Revisionable;

class Representante extends Eloquent implements Revisionable {

  use RevisionableTrait;

  protected $fillable = ['nome', 'telefone', 'email'];
  protected $revisionable = ['nome', 'telefone', 'email'];


  public function clientes()
  {
    return $this->hasMany('App\Models\Cliente');
  }

}

Best regards.

Get revisions of a sub-object

It seems to be impossible to get revisions of a sub-object using directly revisionable.

Example :
Contact object has many Phone objects. A phone is deleted. Then I have no way to retrieve revisions of this object using the Contact object.

I think this could be a great feature to add !

Many thanks for this package btw !

publishing config failes

the following error occurs:

[Symfony\Component\Debug\Exception\FatalThrowableError]
Type error: Argument 2 passed to Sofa\Revisionable\Laravel\RevisionsTableCo
mmand::__construct() must be an instance of Illuminate\Foundation\Composer,
instance of Illuminate\Support\Composer given, called in /home/vagrant/Cod
e/Personal/PHP/Application/Web/vendor/sofa/revisionable/src/Laravel/ServicePr
ovider.php on line 143

Presenters not working

First I find a ticket.

$tick = App\Tickets::find(14);

Then I find a revision for the same:

$rev = $tick->latestRevision;

But it gives me a error:

App\Presenters\Revisions\Tickets #0000000021ba4aef0000000179e23051 {}

When I see in database, the revisions table is updated with a revision.

And this is my Presenters code:

namespace App\Presenters\Revisions;

use Sofa\Revisionable\Laravel\Presenter;

class Tickets extends Presenter {

protected $passThrough = [
        'stage_id'        => 'ticket_stages.stage_name',
        'assigned_to'    => 'users_details.user_name',
    ];
protected $actions = [
        'created'  => 'Created at',
        'updated'  => 'Updated at',
        'deleted'  => 'Deleted',
        'restored' => 'Restored',
    ];
}

Display Revisions

Hi there,

Thanks for this great framework! I have it logging revisions successfully which has saved me a lot of time.

With regards to retrieving the revisions for a particular model, do you have an example on how to do that?

Here is an example of how to do it in VentureCraft/revisionable:

@foreach($account->revisionHistory as $history )
    <li>{{ $history->userResponsible()->first_name }} changed {{ $history->fieldName() }} from {{ $history->oldValue() }} to {{ $history->newValue() }}</li>
@endforeach

Thanks,

Nathan

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.