我想在laravel 5.3中使用json解析数据,但收到消息
未定义的属性:Illuminate \ Support \ Collection :: $ bulan
public function chart()
{
$bulan = [];
$jumlah = [];
$data[] = DB::table('data_peminjaman')
->select(DB::raw("DATE_FORMAT(created_at,'%Y') as tahun ,DATE_FORMAT(created_at,'%M') as bulan,COUNT(*) as jumlahdata, DATE_FORMAT(created_at,'%m') as b"))
->groupBy(DB::raw("DATE_FORMAT(created_at,'%M'),DATE_FORMAT(created_at,'%Y'),DATE_FORMAT(created_at,'%m')"))
->orderBy('tahun')
->orderBy('b')
->get();
foreach ($data as $key ) {
array_push($bulan, $key->bulan);
array_push($jumlah, $key->jumlahdata);
}
// return view('chart',$data);
return view('chart', compact('bulan', 'jumlah'));
}
答案 0 :(得分:3)
代替:
$data[] = DB::table('data_peminjaman')
->select(DB::raw("DATE_FORMAT(created_at,'%Y') as tahun ,DATE_FORMAT(created_at,'%M') as bulan,COUNT(*) as jumlahdata, DATE_FORMAT(created_at,'%m') as b"))
->groupBy(DB::raw("DATE_FORMAT(created_at,'%M'),DATE_FORMAT(created_at,'%Y'),DATE_FORMAT(created_at,'%m')"))
->orderBy('tahun')
->orderBy('b')
->get();
您应该使用:
$data = DB::table('data_peminjaman')
->select(DB::raw("DATE_FORMAT(created_at,'%Y') as tahun ,DATE_FORMAT(created_at,'%M') as bulan,COUNT(*) as jumlahdata, DATE_FORMAT(created_at,'%m') as b"))
->groupBy(DB::raw("DATE_FORMAT(created_at,'%M'),DATE_FORMAT(created_at,'%Y'),DATE_FORMAT(created_at,'%m')"))
->orderBy('tahun')
->orderBy('b')
->get();
这里唯一的区别是$data[]
与$data
。
也可以代替
:foreach ($data as $key ) {
array_push($bulan, $key->bulan);
array_push($jumlah, $key->jumlahdata);
}
您可以使用pluck方法:
$bulan = $data->pluck('bulan');
$jumlah = $data->pluck('jumlahdata');