'Laravel 9.5.1 Undefined Variable on return view

Good day, I'm having a problem on passing data from controller to the blade.

This is the code from controller:

function dashboard(){
        $adminData = ['LoggedAdminInfo'=>Admin::where('id','=',session('LoggedAdmin'))->first()];
        $sensor_latest_data = array('list'=>DB::table('sensors')->latest('id')->first());
        $sensor_data = Sensor::select('id', 'created_at')->get()->groupBy(function($data) {
            return Carbon::parse($data->created_at)->format('M');
        });
        return view('admin.index', $adminData, $sensor_latest_data, ['chart_data'=>$sensor_data]);
    }

enter image description here

The other data is working fine except for the last argument on return view.

I tried putting it inside the compact() function and it returned this: return view('admin.index', $adminData, $sensor_latest_data, compact(['chart_data'=>$sensor_data]));

enter image description here



Solution 1:[1]

Compact function gets the variable name from string and map it to an array. For exmaple if you use compact('test'), it will search for test variable and map it and return it as ['test' => $test]

return view('admin.index', ['adminData' => $adminData, 'sensor_latest_data' => $sensor_latest_data, 'chart_data'=>$sensor_data]);

or just change your function to :

function dashboard(){
    $adminData = ['LoggedAdminInfo'=>Admin::where('id','=',session('LoggedAdmin'))->first()];
    $sensor_latest_data = array('list'=>DB::table('sensors')->latest('id')->first());
    $chart_data = Sensor::select('id', 'created_at')->get()->groupBy(function($data) {
        return Carbon::parse($data->created_at)->format('M');
    });
    return view('admin.index', compact('adminData', 'sensor_latest_data', 'chart_data'));
}

and here is simplified version:

function dashboard(){
    $LoggedAdminInfo = Admin::where('id','=',session('LoggedAdmin'))->first();
    $list = DB::table('sensors')->latest('id')->first();
    $chart_data = Sensor::select('id', 'created_at')->get()->groupBy(function($data) {
        return Carbon::parse($data->created_at)->format('M');
    });

    return view('admin.index', compact('LoggedAdminInfo', 'list', 'chart_data'));
}

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