honeyBear's avatar

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed

(Post Model)

class Post extends Model { protected $fillable = [ 'title', 'description', 'prize', 'location', 'image', 'user_id' ];

public function user()
{
    return $this->belongsTo('App\User');
}

}

(Migration Schema)

public function up() { Schema::create('posts', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('user_id'); $table->string('title'); $table->mediumtext('description'); $table->decimal('prize'); $table->string('location'); $table->string('image'); $table->timestamps(); }); }

(PostsController)

public function store(Request $request, User $user) { $this->validate($request, [ 'title' => 'required', 'description' => 'required', 'prize' => 'required', 'location' => 'required', 'image' => 'image|max:1999' ]);

    if($request->hasFile('image'))
    {
        //Get file name with the extension
        $fileNameExtension = $request->file('image')->getClientOriginalName();
        //Get just filename
        $fileName = pathinfo($fileNameExtension, PATHINFO_FILENAME);
        //Get just extension
        $extension = $request->file('image')->getClientOriginalExtension();
        //File name to store
        $fileNameToStore = $fileName.'_'.time().'.'.$extension;
        //Upload image
        $path = $request->file('image')->storeAs('public/posts_image', $fileNameToStore);
    }
    else 
    {
        $fileNameToStore = 'default.jpg';
    }
    
    $post = new Post();
    $post->user_id = $user->id;
    $post->title = $request->input('title');
    $post->description = $request->input('description');
    $post->prize = $request->input('prize');
    $post->location = $request->input('location');
    $post->image = $fileNameToStore;
    $post->save();
    
    return redirect('/posts')->with('success', 'Post Created');
}

May I know what's the problem here? I assigned the associated user_id foreign key to the associated id of the user.

0 likes
18 replies
Nakov's avatar

None of your fields is nullable in the database, so try:

dd($request->all(), $user->id);

before you create the post and make sure that all the fields have value.

tykus's avatar

Which column is identified in the SQL error?

My guess is user_id since the validation rules should catch all of the other inputs. So how can $user->id be null... if the User instance is in memory only... which can result from mismatched route wildcard and Controller action method parameter. Does the route wildcard have {user} like the name of your method parameter?

honeyBear's avatar

array:5 [ "_token" => "yRcbQXbavUcJOpANL8KqflF5zlXPFrrG3QhqRQsE" "title" => "title" "prize" => "2000.50" "location" => "location" "description" => "

description

" ] null

honeyBear's avatar

However, I tried set

$post->user_id = auth()->user->id;

It work by assigning the correct user_id, its just when I logged out. And try to access by typing the link localhost:8000/posts/create then fill in the usual, it fail to find the id. Is it because I'm not logged in?

tykus's avatar

posts.user_id

See my updated post above. I believe the User instance is in-memory only because the wildcard is incorrect.

tykus's avatar

Is the user id supposed to come from the URL or from the session?

honeyBear's avatar

GET|HEAD | posts/create | posts.create | App\Http\Controllers\PostsController@create | web POST | posts | posts.store | App\Http\Controllers\PostsController@store | web

tykus's avatar

So you're not getting the user_id from a URL segment! Laravel is simply resolving a User instance from the container.

If you must be logged in, then auth()->id() will given you the currently authenticated user's id; otherwise you are going to have to either find another way to pass the user id (form input) or make the column nullable.

honeyBear's avatar

So my routes wildcard is mismatched from my controller action parameters?

tykus's avatar

You do not have a route wildcard; I assumed you did since there was a type-hinted User in the method signature. instead, Laravel is simply resolving a User instance from the container (this is in memory, i.e. no database record behind it), hence no $user->id

honeyBear's avatar

Because I am using a resource controller at my routes web.php

tykus's avatar
tykus
Best Answer
Level 104

Sure, but why are you typehinting a User in thestore method; this is the source of your issues. As I mentioned earlier, you can get the authenticated user's id from the auth guard using auth()->id(), but this will not work if unauthenticated users can submit the form

1 like
honeyBear's avatar

If I use the auth()->id() method to get the user id then I uses guards and policy to ensure that non unauthenticated are not able to submit the form. Is it a good approach?

tykus's avatar

You use the auth middleware.

Route::resource('posts', 'PostController')->middleware('auth');

Or more likely, there will be more routes that are protected, so you can have an auth group:

Route::middleware('auth')->group(function () {
    // All routes and resource routes defined in this Closure are protected by the `auth` middleware
    Route::resource('posts', 'PostController');
    // other routes...
});

https://laravel.com/docs/6.0/routing#route-group-middleware

1 like
honeyBear's avatar

Thank you for your explaination, appreciate it :-)

tykus's avatar

No worries. Please mark the best reply above to help others

Please or to participate in this conversation.