laravel-auditing: Can't get Audit Users when User Model uses non-default Primary Key
Q | A |
---|---|
Bug? | yes |
New Feature? | no |
Framework | Laravel |
Framework version | 5.4.25 |
Package version | 4.0.7 |
PHP version | 7.0.18 |
Actual Behaviour
It is not possible to get a Model Audit’s User if the User Model uses a non-default Primary Key (ie. a Primary Key different than id
).
Expected Behaviour
It should be possible 😃
Steps to Reproduce
- Setup Laravel and Auditing.
- Change the
App\User
model’s Primary Key to something else (likesome_id
) both in the Model (via theprotected $primaryKey
property) and the database. - Add an auditable model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Auditable;
use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
class SomeModel extends Model implements AuditableContract
{
use Auditable;
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'field1', 'field2', 'field3',
];
}
- Add a table for the new model with a migration with:
Schema::create('some_models', function (Blueprint $table) {
$table->increments('id');
$table->string('field1');
$table->string('field2');
$table->string('field3');
});
- Run a simple test like:
public function testAudits()
{
$modelFields = [
'field1' => 'Field '.rand(),
'field2' => 'mail'.rand().'@mail.com',
'field3' => 'password'.rand(),
];
$model = new SomeModel($modelFields);
// set a proper ID in here
Auth::onceUsingId(1);
$model->save();
// get model with audits and users
$model = SomeModel::with('audits.user')->find($model->getKey());
echo "model: \n";
print_r($model->attributesToArray());
$audit = $model->audits->first();
echo "audit: \n";
print_r($audit->attributesToArray());
$user = $audit->user;
echo "user: \n";
print_r($user->attributesToArray());
}
Result:
1) Tests\Unit\SomeModelTest::testAudits
Error: Call to a member function attributesToArray() on null
(on the print_r($user->attributesToArray());
line)
Possible Solutions
I got it working by adding a 'user_id'
parameter to the Audit::model() method so it looks like:
public function user()
{
return $this->belongsTo(Config::get('audit.user.model'), 'user_id');
}
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 20 (10 by maintainers)
I have a similar situation. I have a non-default primary id which is a VARCHAR and the Audit fails with the following exception:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: ‘hotmail.com’ for column ‘auditable_id’ at row 1.
The model primary key is VARCHAR but the ‘auditable_id’ is BIGINT. I have changed the ‘auditable_id’ to varchar but I am not sure whether this will affect the package’s functionality.
Good catch! It’s done, now.