title: Laravel faker - Generate random user_id for the tasks table
body: <p>for my tasks table I keep getting <em>SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null</em> when i run <code>php artisan migrate --seed</code></p>
  
  <p>Here's my code for <strong>TasksFactory.php</strong></p>
  
  <pre><code>use App\User;
  use App\Model\Task;
  use Faker\Generator as Faker;
  use Illuminate\Database\Eloquent\Model;
  
  $factory-&gt;define(Task::class, function (Faker $faker) {
      $title = $faker-&gt;sentence;
      return [
          'title' =&gt; $title,
          'slug'  =&gt;  str_slug($title),
          'description'   =&gt; $faker-&gt;text,
          'user_id' =&gt; function () {
              return User::all()-&gt;random();
          }
  
          /**
           * I've also tried this
           * 
           *  'user_id' =&gt; function () {
              return factory(App\User::class)-&gt;create()-&gt;id;
          }
           */
      ];
  });
  </code></pre>
  
  <p>Here's my DatabaseSeeder</p>
  
  <pre><code>use App\User;
  use App\Model\Task;
  use Illuminate\Database\Seeder;
  
  class DatabaseSeeder extends Seeder
  {
      /**
       * Seed the application's database.
       *
       * @return void
       */
      public function run()
      {
          factory(User::class, 3)
          -&gt;create()
          -&gt;each(function ($u) {
               $u-&gt;tasks()-&gt;save(factory(Task::class)-&gt;make());
           });
      }
  }
  </code></pre>
  
  <p>and my task Model looks like this with Mass Assignment set to $guarded = [] and user() method for relationship with tasks</p>
  
  <pre><code>namespace App\Model;
  
  use App\User;
  use Illuminate\Support\Facades\Auth;
  use Illuminate\Database\Eloquent\Model;
  
  class Task extends Model
  {
      protected $guarded=[];
  
  
      protected static function boot()
      {
          parent::boot();
  
          static::creating(function ($task) {
              $task-&gt;slug = str_slug($task-&gt;title);
              $task-&gt;user_id = auth()-&gt;id();
          });
      }
  
      public function getRouteKeyName()
      {
          return 'slug';
      }
  
      public function user()
      {
          return $this-&gt;belongsTo(User::class);
      }
  
      public function getPathAttribute()
      {
          return "/task/$this-&gt;slug";
      }
  }
  </code></pre>