php - Call to a member function storeAs() on null while uploading image
Get the solution ↓↓↓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');
Answer
Solution:
When you're uploading Images to Laravel, you need to include the properenctype
:
<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 includeenctype="multipart/form-data"
,$request->file('book_image')
will always benull
.
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 wordpublic
from thesaveAs()
method:
'image' => $request->file('book_image')->storeAs('images', uniqid().'.jpg')
That way, it should work withasset()
helper.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: string literal contains an unescaped line break
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.