Search code examples
phplaravellaravel-8laravel-9

Larvel 9 Edit/Update functionality returning Call to a member function store() on null


I have a blog where I am creating an update function and I removed the required parameter from my 'image' field and set it to 'nullable' since it makes sense to give the user an option to change the image if they want to or not after creating their post.

Update function

public function update(Request $request, Posts $post) {
    $formFields = $request->validate([
        'title' => 'required|min:3|max:50',
        'image' => 'nullable|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
        'sub_title' => 'required|min:3|max:100',
        'tags' => 'required|min:3|max:20',
        'content' => 'required',
        'featured' => 'nullable',
    ]);

    $image_path = $request->file('image')->store('thumbnails', 'public');

    if($request->has('featured')) {
        Posts::where('featured', '=',1)
        ->update(['featured' => false]);
    }

    $post->update([
        'title' => $request->post('title'),
        'image' => $image_path,
        'sub_title' => $request->post('sub_title'),
        'tags' => $request->post('tags'),
        'content' => $request->post('content'),
        'featured' => ($request->has('featured')) ? true : false,
    ]);

    return redirect('/')->with('message', 'Post updated successfully!');  
}

More specifically, the error is being pointed out on this line:

$image_path = $request->file('image')->store('thumbnails', 'public');

Solution

  • You should call the store method only when you have new image file:

    $image_path = $request->file('image')?->store('thumbnails', 'public');
    

    and then add $image_path to attributes only when you have new image:

    $attributes = [
            'title' => $request->post('title'),
            'sub_title' => $request->post('sub_title'),
            'tags' => $request->post('tags'),
            'content' => $request->post('content'),
            'featured' => ($request->has('featured')) ? true : false,
        ];
    
    if ($image_path) {
        $attributes['image'] = $image_path;
    }
    
    $post->update($attributes);