Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving foreign key user_id to posts table

Tags:

php

laravel

I'm developing a laravel application with user and post model and i'm getting an error of:

Field 'user_id' doesn't have a default value

I have set up relationships for both models. Post belongs to user and a user can have as many posts. The user_id is not being saved to the post table in the database.

Post Controller:

class PostController extends Controller

{
    public function postCreatePost(Request $request){

        $this->validate($request, [

            'body' => 'required'

        ]);

        $post = new Post([

           'body' => $request->input('body') 

        ]);

        $post->save();

        return redirect()->route('dashboard');

    }

Route:

Route::post('/createpost', [

    'uses' => 'PostController@postCreatePost',
    'as' => 'post.create'

]);
like image 291
steven Avatar asked Mar 11 '26 15:03

steven


2 Answers

You need to specify user_id:

$post = new Post([
    'body' => $request->input('body'),
    'user_id' => auth()->user()->id
]);

Or you could use relationship:

$user = auth()->user();
$user->posts()->create(['body' => $request->input('body')]);

Also, don't forget to add user_id to the $fillable array in the Post model.

like image 56
Alexey Mezenin Avatar answered Mar 13 '26 05:03

Alexey Mezenin


The reason is you are not giving a user_id when saving a post.

One solution is.

$post = new Post([

     'body' => $request->input('body'), 
     'user_id' => $your_use_id
]);
like image 40
Gayan Avatar answered Mar 13 '26 05:03

Gayan