You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.6按类型筛选电影时出现foreach参数无效错误

Fixing "Invalid argument supplied for foreach()" When Filtering Movies by Genre in Laravel 5.6

Hey there! I’ve been right where you are—staring at that frustrating foreach error even though dd() shows results. Let’s break down the most likely issues and fix this step by step.

First, Let’s Understand the Error

This error pops up because the foreach() loop in your view is trying to iterate over something that’s not an array or iterable collection (like a single model instance, null, or a non-collection value). Even if dd() shows results, there’s a disconnect between what you’re passing to the view and what the view is trying to loop through.

1. Double-Check Variable Names Between Controller & View

I’ve seen this happen way too often: you pass a variable with one name from the controller, but try to loop over a different name in the view.

For example, if your controller has:

// MoviesController.php
public function genre($genre)
{
    $movies = Movie::where('genre', $genre)->get();
    return view('genre', compact('movies')); // Passing $movies
}

Make sure your view is looping over $movies, not a typo like $movie or $movieList:

<!-- genre.blade.php -->
@foreach($movies as $movie) <!-- Match the variable name from the controller! -->
    <!-- Your movie display code -->
@endforeach

2. Ensure Your Query Returns a Collection, Not a Single Model

If you accidentally use first() instead of get() in your query, you’ll get a single Movie instance instead of a collection of movies. foreach() can’t loop over a single object!

✅ Correct query (returns a collection):

$movies = Movie::where('genre', $genre)->get();

❌ Wrong query (returns a single model or null):

$movies = Movie::where('genre', $genre)->first(); // Single model, not iterable

3. Handle Empty Results with @forelse (Laravel’s Secret Weapon)

Even if your query returns an empty collection (which is iterable), it’s good practice to handle empty states—and this also prevents edge cases where something unexpected slips through. Laravel’s @forelse directive is perfect for this:

<!-- genre.blade.php -->
<h1>Movies in {{ $genre }} Genre</h1>

@forelse($movies as $movie)
    <div class="movie-card">
        <h3>{{ $movie->title }}</h3>
        <p>Release Year: {{ $movie->release_year }}</p>
        <!-- Add other movie details here -->
    </div>
@empty
    <p class="text-muted">No movies found for this genre. 😢</p>
@endforelse

This will gracefully show a message when there are no movies, instead of throwing an error.

4. Verify No Code Overwrites Your Variable After dd()

If you placed dd($movies) before returning the view, double-check that no code after the dd() modifies the $movies variable. For example:

$movies = Movie::where('genre', $genre)->get();
dd($movies); // Shows results here
$movies = someHelperFunctionThatReturnsNull(); // Oops, overwrote the variable!
return view('genre', compact('movies'));

Comment out or remove the dd() once you’ve confirmed the initial query works, and make sure no later code changes the variable.

5. Check Route & Parameter Handling

Ensure your route is correctly passing the genre parameter to the controller:

// web.php
Route::get('/movies/genre/{genre}', 'MoviesController@genre');

And your controller method is properly receiving it:

public function genre($genre)
{
    $movies = Movie::where('genre', $genre)->get();
    return view('genre', compact('movies', 'genre')); // Pass $genre to the view if needed
}

If the parameter isn’t being passed correctly, your query might return unexpected results (like an empty collection, or even null if there’s a typo in the field name).

Quick Test to Confirm

After making these changes, try filtering for a genre you know has movies. If it works, great! If not, add dd($movies) right before returning the view—this will show you exactly what’s being passed to the view. If it’s a collection (even empty), the @forelse will handle it. If it’s something else (like null or a single model), you’ll know where to fix the query.

内容的提问来源于stack exchange,提问作者Programming Bat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:18:46