When I’m going to add data an error appears “Call to a member function count() on null”
View
@foreach ($data as $row) <tr> <td>{{ $row->customer}}</td> <td>{{ $row->vessel}}</td> <td>{{ $row->scopejob}}</td> <td>{{ $row->pergantian_sparepart}}</td> <td>{{ $row->teknisi}}</td> <td>{{ $row->tahun}}</td> <td>{{ $row->keterangan}}</td> <td>{{ $row->images->count()}}</td> <td>{{ $row->files->count()}}</td> <td> <a href={{route('data.images',$row->id)}} type="button" class="btn btn-info m-1">FOTO</a> <a href={{route('data.files',$row->id)}} type="button" class="btn btn-info m-1">FILE</a> <a href="/show_rekap/{{ $row->id}}" class="btn btn-warning m-1">EDIT</a> <a href="#" class="btn btn-danger delete m-1" data-id="{{ $row->id}}" data-customer="{{ $row->customer}}" >DELETE</a> </td> </tr> @endforeach
Controller rekap
:
public function insert_rekap(Request $request) { // dd($request->all()); $this -> validate($request,[ 'customer'=>'required', 'vessel'=>'required', 'scopejob'=>'required', 'pergantian_sparepart'=>'required', 'teknisi'=>'required', 'tahun'=>'required', 'keterangan'=>'required' ]); $data = rekap::create($request->all()); if($request->hasFile("images")){ $images=$request->file("images"); foreach($images as $image){ $imageName=time().'_'.$image->getClientOriginalName(); $request['rekap_id']=$data->id; $request['image']=$imageName; $image->move(public_path("/images_rekap"),$imageName); Image_rekap::create($request->all()); }if($request->hasFile("files")){ $files=$request->file("files"); foreach($files as $file){ $fileName=time().'_'.$file->getClientOriginalName(); $request['rekap_file_id']=$data->id; $request['file']=$fileName; $file->move(public_path("/rekap_file"),$fileName); file_rekap::create($request->all()); } } } return redirect()->route('rekap')->with('success','Data Berhasil Ditambahkan'); }
but the data is successfully entered into the database, and what steps should I take to correct the error
Advertisement
Answer
error tells you that images
or files
or both variables are null, looks like you don’t use eager loading
quick and dirty way is to use optional helper
<td>{{ optional($row->images)->count()}}</td> <td>{{ optional($row->files)->count()}}</td>
if you need only count then better approach is to use eloquent counting related models
// controller $data = rekap::withCount(['images', 'files']) // other selecting rules //->where ... ->get(); return view('view_name', ['data'=>$data]);
now in every $row of $data you have fields images_count
and files_count
<td>{{ $row->images_count }}</td> <td>{{ $row->files_count }}</td>
also you can rename count variables like rekap::withCount(['images as imagesCount', 'files as filesCount'])
<td>{{ $row->imagesCount }}</td> <td>{{ $row->filesCount }}</td>