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]);
}
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]));
CodePudding user response:
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'));
}