An observer needs to be created where in the method before creating a new record (creating
) can set a value for this model
, a minimal example:
Created a model inside the folder App
by the name of Test
:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Test extends Model
{
protected $fillable = ['name','user_id'];
protected $primaryKey = 'id';
}
Create inside the folder App
another folder named after Observers
and inside that folder a TestObserver.php
with the following code:
<?php namespace App\Observers;
use App\Test;
class TestObserver
{
public function creating(Test $model)
{
$model->user_id = auth()->user()->id;
}
}
and for this note to run at the time before saving the data in the database in the folder app\Providers
open the file AppServiceProvider
and within the method boot
add the following line:
Test::observe(TestObserver::class);
Attention: don’t forget to put the uses
, complete example of AppServiceProvider.php
:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Observers\TestObserver;
use App\Test;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
Test::observe(TestObserver::class);
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
with these appropriate settings every time you try to create a new record for a particular model
automatically configured the value of the logged in user will be passed to the model
and soon after will be saved with the other data that has already been passed.
Note that in addition to the method creating
which refers to the model before saving the data there are others like:
- retrieved
- Creating
- created
- updating
- updated
- saving
- saved
- deleting
- Deleted
- Restoring
- Restored
which can be configured, but the given example refers to your question.
Reference:
The answer didn’t work?
– novic