Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I have an 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading