warpig's avatar
Level 12

'post_id' cannot be null

Hi all, im trying to store a new post but i get the following message: https://flareapp.io/share/dPb4XnJ5

It seems like I can't attach a tag to a post even though iv'e set this relationship a while ago, recently I added the image upload functions and im not sure if that altered somehow the logic of the functionality.

These are how both relationships look like:

class Tag extends Model
{   
    public function posts()
    {
        return $this->belongsToMany('App\Models\Post');
    } 

    use HasFactory;
}

Inside the Post model

public function tags()
    {
        return $this->belongsToMany('App\Models\Tag')->withTimeStamps();
    }
0 likes
4 replies
warpig's avatar
Level 12

This is how im storing everything regarding a post:

    protected function validatePost() 
    {
        return request()->validate([
            'title' => 'required|max:255',
            'body'  => 'required',
            'slug'  => 'required|max:100',
            'tags' => 'exists:tags,id'
        ]);
    }
MichalOravec's avatar
Level 75

You need to first save a post.

public function store(Request $request)
{
    $this->validatePost();

    $post = new Post(request(['title', 'body', 'slug', 'image_url']));

    $fileExtension = request('image')->getClientOriginalName();

    $fileName = pathInfo($fileExtension, PATHINFO_FILENAME);

    $extension = request('image')->getClientOriginalExtension();

    $newFileName = $fileName . '_' . time() . '.' . $extension;

    $imgPath = request('image')->storeAs('public/img/post_uploads', $newFileName);

    $user = auth()->user();

    $post->image_url = $newFileName;

    $post->user_id = $user->id;

    $post->save();

    $post->tags()->attach(request('tags'));

    return redirect('/posts');
}
MichalOravec's avatar

I would change it to something like this

public function store(Request $request)
{
    $this->validatePost(); // use a form request

    $post = Post::create($request->only([
        'title', 'body', 'slug', 'image_url'
    ] + [
        'user_id' => auth()->id()
    ]);

    if ($request->hasFile('path')) {
        $name = pathInfo($request->image->getClientOriginalName(), PATHINFO_FILENAME).'_'.time().'.'.$request->image->getClientOriginalExtension();

        $request->image->storeAs('public/img/post_uploads', $name);

        $post->image_url = $name;
    }

    $post->tags()->attach($request->tags);

    return redirect('/posts');
}

Please or to participate in this conversation.