Eloquent Laravel - Column user_id

1

Hello, I'm learning laravel and I do not find this in any forum. I have some tables that have a foreign key called 'user_id', but when I save an object in the database I always have to fill that column. Is there a way to do this? I want to be able to create an object in the same way.

Here's how I'm doing:

$data = $request->all();
$data['user_id'] = auth()->user()->id;
UmObjetoQualquer::create($data)
    
asked by anonymous 08.05.2018 / 03:36

2 answers

0

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.

08.05.2018 / 04:47
0

You just put the "user_id" field in fillables on the User model.

class User extends Authenticatable
{
    use Notifiable;
    use EntrustUserTrait;

    protected $fillable = [
        'id','name', 'email', 'password','user_id'
    ];


    protected $hidden = [
        'password', 'remember_token',
    ];

}

This way you will not have to specify to save, like the other fields.

    
08.05.2018 / 23:30