Created a model inside the folder creating
with the name of model
:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Test extends Model
{
protected $fillable = ['name','user_id'];
protected $primaryKey = 'id';
}
Create another folder named App
inside the folder Test
and within that folder a App
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 to be executed at the moment before saving the data in the base in the Observers
folder, open the file TestObserver.php
and within the app\Providers
method add the following line:
Test::observe(TestObserver::class);
Warning: do not forget to put AppServiceProvider
, complete example of boot
:
<?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 settings every time you try to create a new record for a given uses
, the value of the logged in user is automatically passed to AppServiceProvider.php
and then saved with the other data that has already been passed.
Note that in addition to the model
method that refers to the template before saving the data, there are others like:
- retrieved
- creating
- created
- updating
- updated
- saving
- saved
- deleting
- deleted
- restoring
- restored
that can be configured, but the given example is about your question.