Q:

Saving foreign key user_id to posts table

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'

]);

A:

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.

