简体   繁体   中英

Using a database request in a custom helper Laravel

I'm using a laravel custom helper to print data in my view blade file. I pass a foreign key from a table to the custom helper and the custom helper checks the foreign key and returns its associated data. Recently my colleage suggested it is a bad idea to use a custom helper in a foreach loop of a view file. I didn't experience any performance issues, however my colleague suggested that when uploading to an AWS server, each request to the database would be charged. This is my code:

<?php
  foreach($data as $key => $details) { ?>                                            
    <td>{{ helper::getstatename($details>stateid)}}</td> 
  <? }
?>

This is the helper file:

public static function getstatename($id) {
  $getstatename = states::select('statename','id')->where('id',$id)->first();
  if($getstatename){
    return $getstatename->statename != '' ? $getstatename->statename : '';
  } else {
    return false;
  }
}

My controller:

public function index() {
  $locations = DB::table('locations')->select('locations.id','locations.locationname','cityid','stateid','countryid','locations.status')
    ->where('locations.status','!=',2)->orderBy('id','desc')->get(); 
  return view('location/listlocation',['data'=>$locations]);
}

So I want to know, is this practice of using a helper file bad? Or should I stick to using a left join and print that data?

better you use joins to get state name at the $locations in the controller itself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM