Laravel 5.8多图上传报错:Undefined variable: data,求问题排查
Hey there! Let's break down why you're hitting that "Undefined variable: data" error and how to fix it quickly.
The Root Cause
The issue pops up when a user submits the form without uploading any files. In this scenario, $request->file('filename') returns null, so your if block never executes. That means the $data variable is never created—but you still try to use it later with json_encode($data). PHP throws an error because it can't find a variable named data that was defined anywhere.
The Simple Fix
All you need to do is initialize the $data variable before checking for uploaded files. This ensures it exists whether the user uploads files or not. Here's your adjusted code:
public function store(Request $request) { // Validate request $this->validate($request, [ 'title' => 'required|min:10', 'body' => 'required|min:20', 'filename' => 'nullable|array', // Add array rule since it's multiple files 'filename.*' => 'file|mimes:jpeg,jpg,png|max:2480' // Add file rule for clarity ]); // Initialize $data as an empty array first $data = []; // Store images if any are uploaded if($request->file('filename')) { foreach($request->file('filename') as $image) { $name = time() . $image->getClientOriginalName(); $image->move(public_path('/images/'), $name); $data[] = $name; } } $post = new Post(); $post->user_id = auth()->user()->id; $post->title = $request->input('title'); $post->body = $request->input('body'); $post->filename = json_encode($data); // Now $data always exists $post->save(); return back()->withMessage('Post created successfully.'); }
Bonus: Laravel Best Practice for File Uploads
Instead of directly using public_path() and move(), consider using Laravel's built-in Storage facade—it's more secure and aligns with Laravel's conventions. Here's how to refactor the upload part:
- First, run
php artisan storage:linkin your terminal to create a symbolic link frompublic/storagetostorage/app/public. - Update the upload code:
if($request->file('filename')) { foreach($request->file('filename') as $image) { $name = time() . $image->getClientOriginalName(); // Store the file in storage/app/public/images Storage::disk('public')->putFileAs('images', $image, $name); // Store the path relative to storage/app/public (so you can access it with asset()) $data[] = 'storage/images/' . $name; } }
This way, you can easily generate URLs to your images using asset($post->filename) in your views.
内容的提问来源于stack exchange,提问作者Diaz Amaliana

