Laravel Blade Foreach Loop Takes upto 18sec to load 100 data - php

Am still pretty new to laravel but there's some very weird issue am facing.
In the Laravel blade view file. It take some crazy amount of seconds to load content to the browser using Foreach method
This is from the admin section controller
$rates = Rate::where('user_id', $user->user_id)
->orderBy('id', 'ASC')
->paginate(100);
return view('admin.users-view', compact('headers', 'rates'));
The query takes about 2sec or less
On the Blade file, the foreach takes about 18sec to display this to the browser and gives me a crazy headache. Please may I know what am doing wrong?
#foreach ($rates as $rate)
<td>{{ data('days', $rate->lead_time) }}</td>
<td>{{ data('kg', $rate->weight) }}</td>
<td>{{ data('format', $rate->dropoff) }}</td>
<td>{{ $rate->tax }}</td>
<td>{{ date("d M Y", strtotime($rate->created_at)) }}</td>
<td>
<a onclick="fetchRate(this)" id="{{ $rate->id }}"
class="edit link"
content="{{ json_encode($rate) }}">
{{ Get_Lang('update', Get_Lang_Cookie()) }}
</a>
</td>
<td>
<a onclick="deleteRate(this)"
id="{{ $rate->id }}" class="edit link">
{{ Get_Lang('delete', Get_Lang_Cookie()) }}
</a>
</td>
</tr>
#endforeach
Rate Table Structure
Schema::create('rates', function (Blueprint $table) {
$table->id();
$table->bigInteger('user_id')->index();
$table->string('origin', 5);
$table->string('destination', 5);
$table->string('lead_time')->nullable();
$table->string('weight');
$table->string('dropoff')->default(0); //price amount
$table->string('tax')->default(0);
$table->timestamp('created_at', 0)->nullable()->index();
$table->timestamp('updated_at', 0)->nullable();
});

Related

Call to a member function count() on null

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>

Laravel throws an error once I have more than 15 rows in my order table ```local.ERROR: Undefined array key 0```

I really don't know how to put it. I have two tables Order.php and Product.php, a return $this->hasMany(Product::class, 'id'); in Order.php and return $this->belongsTo(Order::class, 'product_id'); in Product.php.
In my OrderController
public function index()
{
$orders = Order::latest()->paginate(10);
return view('admin.order.order')->with([
'orders' => $orders,
]);
}
in my view
#foreach($orders as $order)
<tr data-href="{{ route('orders.view', $order->id) }}">
<td></td>
<td>{{ $order->products[0]->product_name }}</td>
<td>{{ $order->order_quantity }}</td>
<td>{{ $order->customer_name }}</td>
<td>{{ $order->customer_tel_no }}</td>
<td width="300">{{ $order->customer_address }} Lorem ipsum dolor sit amet, consectetur adipisicing elit.</td>
<td>{{ $order->total_amount }}</td>
<td>
<span class="badge text-white badge-lg bg-{{ $order->is_delivered == false ? 'warning' : 'success' }}">
{{ $order->is_delivered == false ? 'Not yet delivered!' : 'Delivered!' }}
</span>
</td>
<td>{{ $order->created_at->diffForHumans() }}</td>
</tr>
#endforeach
Everything works fine until, when I have more than 15 records in the orders table I get an error Undefined array key 0
And please I'm also new to Laravel thanks
I would think this happens because of the line:
<td>{{ $order->products[0]->product_name }}</td>
Are you sure you have a product for every order?
This error would be because an $order does not have any products, therefore would have no array key 0
You can make use use php's new optional syntax while chaining which is ?-> https://stitcher.io/blog/php-8-nullsafe-operator
$order->products?->first()->product_name which should return null, if there aren't any products on this particular $order (assuming you are using php 8!)
If you are on an older version of php you should consider
#if(count($order->products))
<td>{{ $order->products[0]->product_name }}</td>
#endif
Yet another approach would be, to use laravel's optional() helper like below
<td>{{ optional($order->products)->first()->product_name }} </td>

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.

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