Call to a member function storeAs() on null while uploading image

Viewed 296

I'm trying to upload image to my database, everything seems on purpose but when I upload the image I get following error:

Call to a member function storeAs() on null

It seems normal but I still get that error.

Controller

function Create(Request $request){
        $book = Book::create([
            'name' => $request->book_name,
            'writer_name' => $request->writer_name,
            'isbn' => $request->book_isbn,
            'image' => $request->file('book_image')->storeAs('public/images', $id.'.jpg'),
        ]);
        $book->save();
        return redirect('/');
    
    }

HTML

<input class="form-control" type="file" name="book_image" id="book_image" placeholder="Image">

Route

Route::post('create','EditController@Create');
1 Answers

When you're uploading Images to Laravel, you need to include the proper enctype:

<form method="POST" action="{{ url('/update') }}" enctype="multipart/form-data">
  @csrf
  <input class="form-control" type="file" name="book_image" id="book_image" placeholder="Image">
  ...
</form>

If you don't include enctype="multipart/form-data", $request->file('book_image') will always be null.

As a sidenote, you should probably add some form of Validation for this to enforce that an image is being uploaded, and it is a valid image format:

https://laravel.com/docs/7.x/validation#rule-required
https://laravel.com/docs/7.x/validation#rule-image

To display the image, you should be able to use the following:

@foreach($books as $book)
  <img src="{{ asset($book->image) }}"/>
@endforeach

Edit: Drop the word public from the saveAs() method:

'image' => $request->file('book_image')->storeAs('images', uniqid().'.jpg')

That way, it should work with asset() helper.

Related