Call to a member function count() on null - php

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>
FOTO
FILE
EDIT
<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

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>

Try
<td>{{ $row->images ? $row->images->count() : '' }}</td>

Related

Laravel data not being displayed

I am trying to read data from a local collections from my mongodb database. Name of database Intuit name of collection post.
Code inside PostController:
<?php
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller{
public function home() {
$posts = Post::with(['user'])->get();
return view('home', ['posts' => $posts->toArray()]);
}}
Code inside Post:
class Post extends Model{
use HasFactory;
protected $fillable = [
'STATUS',
'DDC_CODE',
'TRADE_NAME',
'SCIENTIFIC_CODE',
'SCIENTIFIC_NAME',
'INGREDIENT_STRENGTH',
'DOSAGE_FORM_PACKAGE',
'ROUTE_OF_ADMIN',
'PACKAGE_PRICE',
'GRANULAR_UNIT',
'MANUFACTURER',
'REGISTERED_OWNER',
'UPDATED_DATE',
'SOURCE'
];}
All of the above are the titles of the columns in the table.
Next home.blade.php:
<!DOCTPE html>
<html>
<head>
<title>View Records</title>
</head>
<body>
<table border = "1">
<tr>
<td>Id</td>
<td>STATUS</td>
<td>DDC_CODE</td>
<td>TRADE_NAME</td>
<td>SCIENTIFIC_CODE</td>
<td>SCIENTIFIC_NAME</td>
<td>SCIENTIFIC_CODE</td>
<td>INGREDIENT_STRENGTH</td>
<td>DOSAGE_FORM_PACKAGE</td>
<td>ROUTE_OF_ADMIN</td>
<td>PACKAGE_PRICE</td>
<td>GRANULAR_UNIT</td>
<td>MANUFACTURER</td>
<td>UPDATED_DATE</td>
<td>SOURCE</td>
</tr>
#foreach ($posts as $post)
<tr>
<td>{{ $post->_id }}</td>
<td>{{ $post->STATUS }}</td>
<td>{{ $post->DDC_CODE }}</td>
<td>{{ $post->TRADE_NAME }}</td>
<td>{{ $post->SCIENTIFIC_CODE }}</td>
<td>{{ $post->SCIENTIFIC_NAME }}</td>
<td>{{ $post->INGREDIENT_STRENGTH }}</td>
<td>{{ $post->DOSAGE_FORM_PACKAGE }}</td>
<td>{{ $post->ROUTE_OF_ADMIN }}</td>
<td>{{ $post->PACKAGE_PRICE }}</td>
<td>{{ $post->GRANULAR_UNIT }}</td>
<td>{{ $post->MANUFACTURER }}</td>
<td>{{ $post->REGISTERED_OWNER }}</td>
<td>{{ $post->UPDATED_DATE }}</td>
<td>{{ $post->SOURCE }}</td>
</tr>
#endforeach
</table>
</body>
</html>
The route handler is as follows
Route::get('view','App\Http\Controllers\PostController#home');
all of this seems to be fine but when I load up the application I see nothing but the column titles not sure what I am missing, I believe it is not working because the query in PostController is incorrect and need to change it as it is taken from another projec. Any and all help and suggestions are welcome.
Instead of
Post::with(['user'])->get();
use
Post::with(['user'])->all();
subject to user relationship is properly defined in your Post model
You are sending data as array, But you are trying to get them as object in your blade view file.
Instead of getting data like this:
$post->STATUS
Try using like this:
$post['STATUS']
Don't use ->toArray()
Pass data as below & variables will get displayed
return view('home', ['posts' => $posts)]);

Laravel modify cells with expired date

Sorry I didn´t know how to ask this question, but I want if a file reach his expiration date in each cell of expired date column just put "expired" otherwise just put his expiration date.
In my controller I create an variable called $actualDate= Carbon::now(); and I send it to my view.
In my view I have this on table:
#foreach ($Files as $File)
<tr>
<td><a href="/File/{{$File->id}}">{{
$File->Code}}</td>
<td>{{ $File->created_at }}</td>
<td>{{ $File->person}}</td>
<td>{{ $File->category_file}}</td>
<td>{{ $File->status}}</td>
<td>{{ $File->employed}}</td>
#if($File->expirationDate < $actualDate)
<td>{{$File->expirationDate}}</td>
#else
<td>Expired</td>
#endif
If I put < on comparision all the column will be "expired" and if I put > it will be no expired Files even if there are ¿what can I do to solve this? I hope you can help me.
Try it:
#foreach ($Files as $File)
<tr>
<td><a href="/File/{{$File->id}}">{{ $File->Code}}</td>
<td>{{ $File->created_at }}</td>
<td>{{ $File->person}}</td>
<td>{{ $File->category_file}}</td>
<td>{{ $File->status}}</td>
<td>{{ $File->employed}}</td>
#if(\Carbon\Carbon::parse($File->expirationDate)->lessThan(\Carbon\Carbon::now()))
<td>{{$File->expirationDate}}</td>
#else
<td>Expired</td>
#endif
#endforeach
Hope it helps.

Having problem with retriving json data in laravel

I'm working on a laravel project and i'm getting JSON error. I've try few options to solve the issue but did not come up with any solutions.
In this project I've to send multiple data into database onder one "ID". In that ID there are at list 10 data need to insert. So I used JSON format. It saves ok but getting error when I try to pull data.
Here is my code
Controller :
public function newExpenses(Request $request){
$Jexpenses = new Jexpenses;
$json = array(
'des' => $request->description,
'valu' => $request->expenses
);
$Jexpenses->voucher = $request->voucher_no;
$Jexpenses->date = $request->date;
$Jexpenses->description = json_encode($json);
$Jexpenses->expenses = $request->total;
$Jexpenses->remarks = $request->remark;
if($Jexpenses->save()){
$notification = array(
'message' => 'Expenses Saved',
'alert-type' => 'success'
);
}
return redirect()->back()->with($notification);
}
result :
{"des":["Jon","Sam","Pitter"],"valu":["20","30","15"]}
Return Controller:
public function expenses(){
$data = array(
'title' => 'Expenses',
'expenses' => Jexpenses::all()
);
return view('expenses.expenses')->with($data);
}
html :
#foreach ($expenses as $key => $getData)
{{ $array = #json( $getData->description ) }}
<tr>
<td>{{ ++$key }} </td>
<td>{{ $getData->voucher }} </td>
<td>{{ $getData->date }} </td>
#foreach ($array->description as $k => $v)
<td>{{ $array->des['$k'] }}</td>
<td>{{ $array->valu['$k'] }}</td>
#endforeach
<td>{{ $getData->expenses }}</td>
<td>{{ $getData->remarks }}</td>
</tr>
#endforeach
it should be work fine but getting error
error:
syntax error, unexpected '<' (View: C:\xampp\htdocs\acSoft\resources\views\expenses\expenses.blade.php
Need some help. Thanks.
1) Use json_decode($getData->description) instead #json. The #json is shortly form of json_encode
2) $array->description not exists property. Should be $array->des
3) You use variable in ' quotes. You should use " quote or nothing round variables.
4) It is bad idea using reserved words as variable names. I am about variable $array
#foreach ($expenses as $key => $getData)
{{ $descriptionData = json_decode( $getData->description ) }}
<tr>
<td>{{ $key + 1 }} </td>
<td>{{ $getData->voucher }} </td>
<td>{{ $getData->date }} </td>
#foreach ($descriptionData->des as $k => $v)
<td>{{ $descriptionData->des[$k] }}</td>
<td>{{ $descriptionData->valu[$k] }}</td>
#endforeach
<td>{{ $getData->expenses }}</td>
<td>{{ $getData->remarks }}</td>
</tr>
#endforeach

Compare two different columns from two different tables and show other column's data from either table in laravel 5.2

Compare two different columns from two different tables with if statement and show other column's data from either table in laravel 5.2
controller like:
public function labDetails(){
$users = DB::table('users')->lists('lab_name');
$labdetails = Labdetails2::paginate(20);
return View('labdetails')
->with('users', $users)
->with('labdetails', $labdetails);
}
here i want to match users table's 'lab_name' column with labdetails2 table's 'lab_name' column and if they matched show only the related data from labdetails table.
N.B. I am working with an old database where there's no relationship among tables.
views like:
<form action="" method="">
<select name="state" onchange="getValue(this)">
<option value="">Select Lab</option>
#foreach ($users as $key => $user)
<option value="{{ $user }}">{{ $user }}</option>
#endforeach
</select>
<input type="submit" value="Submit">
#foreach ($labdetails as $labdetail)
<tbody>
<tr>
<td>{{ $labdetail->sl }}</td>
<td>{{ $labdetail->lab_name }}</td>
<td>{{ $labdetail->pc_name }}</td>
<td>{{ $labdetail->pc_ip }}</td>
<td>{{ $labdetail->mac1 }}</td>
<td>{{ $labdetail->assetno }}</td>
<td>{{ $labdetail->pc_type }}</td>
<td>{{ $labdetail->processor }}</td>
<td>{{ $labdetail->motherboard }}</td>
<td>{{ $labdetail->ram }}</td>
<td>{{ $labdetail->hdd }}</td>
<td>{{ $labdetail->location }}</td>
<td>{{ $labdetail->department }}</td>
<td>{{ $labdetail->entrydate }}</td>
<td>{{ $labdetail->comment }}</td>
</tr>
</tbody>
#endforeach
Please help me what should I do with the controller & views...
You can retrieve only the matches record this way
$users = DB::table('users')->lists('lab_name'); // this retrieves all lab_name as array.
Then, to retrieve only the matches labdetails
$labdetails = Labdetails2::whereIn('lab_name',$users)->paginate(20);
DB::table('users')
->join('labdetails2', 'users.lab_name', '=', 'labdetails2.lab_name')
->select('labdetails2.lab_name', 'labdetails2.pc_name')
->get()
in select(), white down the fields you required.
Here, labdetails2 and users are the table name.
this code finally worked for me:
public function showLabDetails(Request $request){
$q = $request -> request -> all();
$labdetails = Labdetails2::whereIn('lab_name', $q)->get();
return View('showlabdetails')
->with('labdetails', $labdetails);
}
thanks to everyone for helping me.

Using foreach in Laravel 5.1

I'm new in Laravel. I'm storing 3 types of user in my users table:
admin : user_type_id = 1
agent : user_type_id = 2
farmer : user_type_id = 3
user_type_id column is in the users table.
In one of my Blade files, I want to only show the names of the agents. Here is my foreach loop, which is importing all 3 types of the user (it's showing the names of admins, agents and farmers).
#foreach($farmerPoint->user as $agent)
<tr>
<td>{{ $agent->name }}</td>
<td>{{ $agent->phone }}</td>
</tr>
#endforeach
This is probably more of a logic issue than a Laravel issue. NOTE that I would suggest you limit the $agents instead using your query (where) rather than this way, BUT:
#foreach($farmerPoint->user as $agent)
#if ($agent->user_type_id === 2)
<tr>
<td>{{ $agent->name }}</td>
<td>{{ $agent->phone }}</td>
</tr>
#endif
#endforeach
You can use a simple blade #if() statement like so:
#foreach($farmerPoint->user as $agent)
#if ($agent->user_type_id === 2)
<tr>
<td>{{ $agent->name }}</td>
<td>{{ $agent->phone }}</td>
</tr>
#endif
#endforeach
Or you can use a collection where() since all eager / lazy loaded relations are returned in collections:
http://laravel.com/docs/5.1/collections#method-where
#foreach($farmerPoint->user->where('user_type_id', 2) as $agent)
<tr>
<td>{{ $agent->name }}</td>
<td>{{ $agent->phone }}</td>
</tr>
#endforeach

Categories