Zakkojo Zakkojo - 2 months ago 14
PHP Question

Laravel: saving a serialized copy of my model for history

I need to manage record history for a specific model(s).
So following the example here (https://laravel.com/docs/5.2/eloquent#events) I did something like this in my AppServiceProvider.php file:

use App\SourceModel;
use App\History;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider {

/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
SourceModel::saving(function ($source) {
$his= new History();
$his->record = $source->toJson();
$his->user_id = Auth::User()->id;
$his->saved_id = $source->id;
$his->saved_type = 'App\SourceModel';
$his->save();
});
}

...


The problem is in this way Auth::User() returns NULL...

How can I solve this problem? is there a way to make Auth working in appserviceprovider or should i move my saving event somewhere else?

Answer

Since this closure is called when the model is saving, I would expect this to work assuming there is an authenticated user.

I was able to confirm this does work using tinker:

>>> App\User::saving(function ($user) { echo "AUTH USER ID: " . Auth::user()->id; });
=> null
>>> Auth::login(App\User::find(1));
=> null
>>> App\User::find(1)->save();
AUTH USER ID: 1⏎
=> true

Therefore, I would say that if Auth::user() returns null, this model was saved without an authenticated user and if that can happen you need to add a check:

    SourceModel::saving(function ($source) {
        $his= new History();
        $his->record = $source->toJson();
        $his->user_id = (Auth::check()) ? Auth::User()->id : 0;
        $his->saved_id = $source->id;
        $his->saved_type = 'App\SourceModel';
        $his->save();
    });