简体   繁体   中英

compact(): Undefined variable in Laravel 8

I'm still a beginner in laravel. This time, I got an error code like below

Message the error code :

ErrorException compact(): Undefined variable: countanswer

In my controller :

public function home (Request $request) {
    
    ...

    $arr_spesialis = [];
    foreach ($expert_list as $data) {
    $countanswer = DB::table('questions')
                    ->where('expert_id', '=', $data->id)
                    ->count();
    $data->countanswer = $countanswer;
    }

    $arr_spesialis = [];
    foreach ($expert_popular as $data) {
    $countanswerpopular = DB::table('questions')
                    ->where('expert_id', '=', $data->id)
                    ->count();
    $data->countanswerpopular = $countanswerpopular;
    }

    return view('petani.Tanyapakar.TanyapakarListPakar',compact('user', 'expert_list','expertises_list', 'expert_popular', 'subscribe', 'countanswer'));
}

What should I do with my code? Thank you. And can someone explain why it's getting an error?

Your $countanswer is inside foreach which means that it is created and destroyed within the loop causing it to never remain in the complete scope of function home . Try this:

public function home (Request $request) {
    
    ...

    $arr_spesialis = [];
    $countanswer = 0; // Initialise with zero and define the scope
    foreach ($expert_list as $data) {
    $countanswer = DB::table('questions')
                    ->where('expert_id', '=', $data->id)
                    ->count();
    $data->countanswer = $countanswer;
    }

    $arr_spesialis = [];
    foreach ($expert_popular as $data) {
    $countanswerpopular = DB::table('questions')
                    ->where('expert_id', '=', $data->id)
                    ->count();
    $data->countanswerpopular = $countanswerpopular;
    }

    return view('petani.Tanyapakar.TanyapakarListPakar',compact('user', 'expert_list','expertises_list', 'expert_popular', 'subscribe', 'countanswer'));
}

Explanation

When a variable is created in PHP it can only be used inside the scope it is created. In your case the foreach, now the variable $countanswer will have a value as long as it is inside the loop but as soon as the loop stops and control flow out, the variable will be destroyed making it undefined for remaining scope of the function.

You can also define scope of variables explicitly if there's a need of such action inside your program, read more about PHP Variable Scopes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM