Skip to content
Advertisement

user_id is not taking the value provided

The migrations file look like below

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('title')->unique();
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

but the posts table in the database is having 0 as value.this shows the database

The database is populated through the web.php code below. I need the user_id to have values 1 and 2 in the database posts.

  Route::get('/create',function (){

    $post=Post::create(['title'=>'lara vel','body'=>'laravel is good for php','user_id'=>1]);
    $post=Post::create(['title'=>'spri ng','body'=>' spring is good for java','user_id'=>2]);

  });

Advertisement

Answer

It’s very Simple

just Go to your Post model

when you use create method to insert data you must be use fillable propery in your model.

so if you not have an Post model so create post Model and paste this code inside your Post Model

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Post extends Model
{
    protected $table = 'posts';
    protected $fillable = [
        'user_id', 'title','body'
    ];
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement