I have question about scope yesterday, and someone gives an answer to don't return anything in scope. Is return something in scope really bad practice? Should I not return anything in the model except query?
Rather than scope, I want to create a normal method to return the select2 format. I have so many model/table that I need to return to select2 format, I think it's WET (write every time) if I must write every model or controller. I think I need to use DRY(Don't Repeat Yourself) principle, so I want to use a trait like below:
trait ModelTrait
{
public static function getSelect2format($column = "name")
{
$data = static::select('id', $column.' as text')->orderBy($column, 'asc')->where($column, "like", "%".request()->q."%");
if (is_array(request()->filter) && !empty(request()->filter)) {
foreach(request()->filter as $key => $val)
{
if(in_array($key,$this->filterable))
{
$data = $data->where($key, $val);
}
}
}
$data = $data->limit(5)->get();
return $data;
}
}
I just need to call use ModelTrait
in every model that I need and call it in the controller like below:
public function selectJson()
{
$data = Customer::getSelect2Format("column_name");
return \Response::json($data);
}
Is the code above break the best practice? What are the concerns or something that I need to improve?
$this
. Your method uses$this
on the very first line of its body. Not working code is off-topic on this site. \$\endgroup\$ – slepic Jun 18 '20 at 4:35$this
tostatic::
, Hope you can improve more, Thank you. \$\endgroup\$ – Muhammad Dyas Yaskur Jun 18 '20 at 5:42