'I am using laravel 5.8 while creating the dynamic dropdown for search filter I get an error for Undefined variable: country

I already define the variable here is my code

class MainController extends Controller
{
    public function index()
    {
        $country = Country::all();
        return view ('index',compact($country)); 
    }

    public function getStates($id)
    {
       $states = State::where('country_id', $id)->pluck("name", "id");
       return json_encode($states);
    }
}


Solution 1:[1]

you can do any of the following

1.

public function index()
    {
        $country = Country::all();
        return view('index',compact('country')); 
    }
public function index()
{
    $country = Country::all();
    return view('index',['country' => $country]); 
}

Solution 2:[2]

when use compact write data withoute $ and put it in '' :

 public function index()
{
    $country = Country::all();
    return view ('index',compact('country')); 
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bhola Kr. Khawas
Solution 2 amirhosein hadi