Laravel报错:Call to a member function store() on null 求助排查
That error pops up because $request->file('something') is returning null—meaning your Laravel app isn't receiving the file you're trying to upload. Let's walk through the most common fixes step by step:
1. Double-check your form's enctype attribute
You've included enctype="multipart/form-data" in your form, which is mandatory for file uploads—but make sure there are no typos, and that this attribute is applied directly to the <form> tag (not nested inside another element). Without this, browsers won't send file data to the server at all.
2. Validate the file exists before calling store()
Never assume the file is present—add checks to handle cases where the user forgets to select a file:
public function store(Request $request) { // Check if the file was submitted if (!$request->hasFile('something')) { return back()->with('error', 'Please select a file to upload.'); } // Verify the file is valid (no corruption, etc.) if (!$request->file('something')->isValid()) { return back()->with('error', 'The selected file is invalid.'); } // Now safely store the file $path = $request->file('something')->store('upload'); echo $path; }
3. Confirm the input name matches exactly
Your input has name="something", and you're using $request->file('something')—that looks correct, but double-check for typos, extra spaces, or case sensitivity (though HTML names are case-insensitive, it's best to keep them identical to avoid issues).
4. Check PHP upload limits
If you're trying to upload a large file, it might be getting rejected by PHP's default limits. Edit your php.ini file to adjust these values:
upload_max_filesize: Set to a value larger than your file (e.g.,10Mfor 10MB)post_max_size: Should be larger thanupload_max_filesize(e.g.,12M)
After making changes, restart your web server for them to take effect.
5. Use Laravel's validation for cleaner handling
For a more robust solution, let Laravel's validation system handle the checks automatically:
public function store(Request $request) { // Validate that a file was uploaded $validated = $request->validate([ 'something' => 'required|file', ]); // Store the file once validation passes $path = $request->file('something')->store('upload'); echo $path; }
This will automatically redirect back with error messages if no file is selected.
Bonus: Verify storage directory permissions
Make sure the storage/app/upload directory exists and has proper permissions (usually 755 or 777, depending on your server setup). Laravel's store() method will try to create the directory if it doesn't exist, but it needs write permissions to do so.
内容的提问来源于stack exchange,提问作者Valery

