john
john

Reputation: 21

insert data into hasone table from a form input in laravel

i have two table one is user which is parent and other is posts(child) table and its coulmns are


 public function up(){
        Schema::create('posts', function (Blueprint $table) {

            $table->increments('id');
            $table->integer('user_id');
            $table->string('title');
            $table->string('body');
            $table->timestamps();

        }
   }

i have already specified

$this->hasOne('Post');

relation into user model. now i want to insert data into posts table where with form i can save data into title and body column into there respective id's.

Upvotes: 2

Views: 894

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

If it's an authenticated user, you can do this:

auth()->user()->posts()->create($request->all());

To make create() method work you also need to have $fillable array with all properties in the Post model:

$protected fillable = ['title', 'body'];

Upvotes: 3

Related Questions