我需要管理特定模型的记录历史记录。 所以按照这里的例子(https://laravel.com/docs/5.2/eloquent#events),我在AppServiceProvider.php文件中做了类似的事情:
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();
});
}
...
问题是这样Auth :: User()返回NULL ...
我该如何解决这个问题?有没有办法让Auth在appserviceprovider中工作,还是应该将我的保存事件移到其他地方?
答案 0 :(得分:1)
由于在模型保存时会调用此闭包,因此假设存在经过身份验证的用户,我希望这可以正常工作。
我能够使用修补程序确认这确实有效:
>>> 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
因此,我会说如果Auth::user()
返回null
,则此模型在没有经过身份验证的用户的情况下保存,如果发生这种情况,您需要添加一个检查:
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();
});
答案 1 :(得分:0)
我认为听模型事件的正确位置是EventServiceProvider(App \ Providers \ EventServiceProvider)。
只需将您的代码移至" boot" EventServiceProvider中的方法已经完成。
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use App\SourceModel;
use App\History;
use Illuminate\Support\Facades\Auth;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::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();
});
}
}
注意:您可以包含这样的外观:&#34;使用\ Auth&#34;