Back to Error Center

Undefined variable

Error Message

Undefined variable $posts (View: /resources/views/posts/index.blade.php)

Cause

A variable used in a Blade template wasn't passed from the controller, or the variable name has a typo.

Solution

Check the controller\'s compact() or view data array. Verify the variable name matches between controller and view. Use optional chaining for potentially null values.

Code Example

Fix
// Controller - ensure variable is passed
public function index()
{
    $posts = Post::paginate(15);
    return view('posts.index', compact('posts'));
    // Or: return view('posts.index', ['posts' => $posts]);
}

// View - use the correct variable name
@foreach($posts as $post)
    {{ $post->title }}
@endforeach

Debugging Steps

  1. Check the controller method for the variable name
  2. Verify compact() or view data array
  3. Check for typos in the variable name
  4. Use @dump() to inspect available variables

Prevention

Always pass required variables from controllers. Use IDE support for Blade templates. Consider using View::share() for global variables.