I want to pass the param from the request on the scope method in the model and serve it as json to be rendered by select2. Which is better?
1. Pass request from the controller like this
controller:
public function selectJson(Request $request)
{
$request = Customer::getSelect2($request)
return \Response::json($request);
}
model:
public function scopeGetSelect2($query, $request)
{
$customers = $query->select('id','name')->orderBy('name','asc')->where("name", "like", "%".$request->q."%");
if($request->city_id)
{
$customers = $query->where("city_id", $request->city_id);
}
$customers = $customers->limit(5)->get();
$formatted_tags = [];
foreach ($customers as $customer) {
$formatted_tags[] = ['id' => $customer->id, 'text' => $customer->name];
}
return $formatted_tags;
}
2. Use request() helper in the model
Controller:
public function selectJson()
{
$request = Customer::getSelect2()
return \Response::json($request);
}
Model:
public function scopeGetSelect2($query)
{
$customers = $query->select('id','name')->orderBy('name','asc')->where("name", "like", "%".request()->q."%");
if($request->city_id)
{
$customers = $query->where("city_id", request()->city_id);
}
$customers = $customers->limit(5)->get();
$formatted_tags = [];
foreach ($customers as $customer) {
$formatted_tags[] = ['id' => $customer->id, 'text' => $customer->name];
}
return $formatted_tags;
}
Which is better in performance and best practice? And should I format the return in the model like above codes or in the controller like below:
public function selectJson()
{
$customers = Customer::getSelect2()->limit(5)->get();
$formatted_tags = [];
foreach ($customers as $customer) {
$formatted_tags[] = ['id' => $customer->id, 'text' => $customer->name];
}
return \Response::json($formatted_tags);
}
Or any other method or concern that I need to know?
Thanks in advance