Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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'));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading