Laravel报错:Undefined variable: exams 问题求助
Hey there, let's fix that Undefined variable: exams error you're hitting in your Laravel app. This is a super common issue when data isn't passed correctly from your controller to the view—let's break down how to troubleshoot and resolve it step by step:
First, make sure your ExamController.php is actually fetching exam data and passing the $exams variable to the home view. Here's the correct pattern you need:
namespace App\Http\Controllers; use App\Models\Exam; // Don't forget to import the Exam model! use Illuminate\Http\Request; class ExamController extends Controller { public function home() { // Fetch your exam data (adjust the query to match your needs) $exams = Exam::all(); // Or use Exam::where(...)->get() for filtered results // Pass the $exams variable to the view using compact() or with() return view('home', compact('exams')); // Alternative: return view('home')->with('exams', $exams); } }
If your controller is missing this logic (e.g., it just returns view('home') without passing $exams), the view will never see the variable—this is the most common root cause.
Check your routes/web.php file to ensure the /home route is linked to the home method in ExamController, not a direct view return:
// Correct: Routes to your controller method that passes $exams Route::get('/home', [ExamController::class, 'home']); // Incorrect: Directly returns the view without passing data // Route::get('/home', function() { return view('home'); });
Double-check your home.blade.php to make sure you're using the exact variable name $exams (no singular $exam or misspellings). For example, if you're looping through exams:
// Correct usage with error safety @forelse($exams as $exam) <div>{{ $exam->title }}</div> @empty <p>No exams available right now.</p> @endforelse
Using @forelse instead of @foreach adds a safety net for when there are no exams, and prevents extra undefined variable warnings.
Sometimes old cached views or routes can cause unexpected behavior. Run these commands in your project root to clear them:
php artisan view:clear php artisan route:clear
After going through these steps, reload http://localhost:8000/home—the error should be gone if you've fixed the data passing from controller to view.
内容的提问来源于stack exchange,提问作者MOKADDES

